标签: angular-directive

AngularJS:在html上使用$ compile,其中包含带有templateurl的指令

我有一个遗留应用程序,通过jQuery将一些内容插入到DOM中.我希望代码库的遗留部分负责编译它插入DOM的html.

我可以使用它来编译初始的html $compile,但是不会编译由指令的模板或templateUrl添加的任何DOM元素,除非我$scope.$apply()从指令本身调用.

我在这做错了什么?

链接到小提琴: http://jsfiddle.net/f3dkp291/15/

的index.html

<div ng-app="app">
    <debug source='html'></debug>
    <div id="target"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

的application.js

angular.module('app', []).directive('debug', function() {
    return {
        restrict: 'E',
        template: "scope {{$id}} loaded from {{source}}",
        link: function($scope, el, attrs) {
          $scope.source = attrs.source

          if( attrs.autoApply ) {
              // this works
              $scope.$apply()
          }
        },
        scope: true
    }
})

// mimic an xhr request
setTimeout(function() {
    var html = "<div><debug source='xhr (auto-applied)' auto-apply='1'></debug><br /><debug source='xhr'></debug></div>",
        target = document.getElementById('target'),
        $injector = angular.injector(['ng','app']),
        $compile = $injector.get('$compile'),
        $rootScope …
Run Code Online (Sandbox Code Playgroud)

javascript jquery angularjs angularjs-scope angular-directive

6
推荐指数
1
解决办法
2万
查看次数

AngularJS指令监视父级大小的变化

问题

我有一个简单的指令,执行特定元素的大小更新.这会监视窗口大小并相应地进行调整.

MyApp.directive('resizeTest', ['$window', function($window) {
  return {
    restrict: 'AC',
    link: function(scope, element) {
      var w = angular.element($window);
      scope.$watch(function() {
        return { 'h': w.height(), 'w': w.width() };
      }, function(newValue, oldValue) {
        // resizing happens here
      }, true);
      w.bind('resize', function() { scope.$apply(); });
    }
  };
}]);
Run Code Online (Sandbox Code Playgroud)

这很好用.

恰好在div与之关联的标签内部,我有一个孩子div.调整父级的大小时,我想对子元素进行定位更改.但是,我无法触发.

这会在启动时调用,但在调整元素大小或窗口更改时不会触发:

MyApp.directive('centerVertical', ['$window', function($window) {
  return {
    restrict: 'AC',
    link: function(scope, element) {
      element.css({border: '1px solid #0000FF'});
      scope.$watch('data.overlaytype', function() {
        $window.setTimeout(function() {
          console.log('I am:      ' + element.width() + 'x' …
Run Code Online (Sandbox Code Playgroud)

javascript angularjs angular-directive

6
推荐指数
1
解决办法
1万
查看次数

在React中使用自定义Angular指令

我试图用React渲染来实现替换Angular ng-repeat的"快速重复"模式.我可以渲染一个基本表,但该表需要支持自定义Angular指令.我可以在React(作为属性)中获取自定义指令,但它们不起作用.基于谷歌先生,这应该是可能的,但在我看来,或许我需要在React渲染的HTML上进行$ compile,其中包含我的自定义指令......或者不是.

这是我的精简测试代码.'react-test'指令似乎正确地呈现了ReactClass组件,其中包含一个'ng-monkey'属性,该属性本身就是一个Angular自定义指令.猴子似乎不起作用.有什么建议?

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Angular React Test</title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta content="width=device-width, initial-scale=1.0" name="viewport" />
</head>
<body ng-app="AngularReactTest" ng-controller="TestController">

    <react-test monkey></react-test>

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js">    </script>
    <script src="https://fb.me/react-0.13.3.js"></script>

    <script>
        var ReactClass = React.createClass({
            displayName: 'ReactClass',
            render: function () {
                return (
                    React.DOM.div({ 'data-ng-monkey': '' }, null)
                )
            }
        });

        angular
            .module('AngularReactTest', [])
            .controller('TestController', [function () {
            }])
            .directive('reactTest', function () {
                return {
                    restrict: 'E',                   
                    link: function (scope, el, attrs) {
                        var test = React.createElement(ReactClass, …
Run Code Online (Sandbox Code Playgroud)

angularjs reactjs angular-directive

6
推荐指数
1
解决办法
617
查看次数

Angular在使用指令时给出@ angular/core 404 not found错误

当我将这行代码添加到我的@Component:

directives: [HeroDetailComponent]
Run Code Online (Sandbox Code Playgroud)

代码中断,并给我这个错误:

GET http://localhost:3000/@angular/core 404 (Not Found)
Run Code Online (Sandbox Code Playgroud)

这些是我的脚本index.html:

<script src="node_modules/es6-shim/es6-shim.min.js"></script>
<script src="node_modules/systemjs/dist/system-polyfills.js"></script>
<script src="node_modules/angular2/es6/dev/src/testing/shims_for_IE.js"></script>   

<script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<script src="node_modules/rxjs/bundles/Rx.js"></script>
<script src="node_modules/angular2/bundles/angular2.dev.js"></script>
Run Code Online (Sandbox Code Playgroud)

如果我错过了诊断此问题的任何信息,请告诉我,我会将其包含在此处.

angular-directive angular

6
推荐指数
1
解决办法
3万
查看次数

角度组件将不会显示

我有一些我希望作为组件显示的HTML,因为我没有操纵DOM.

作为一个指令,它工作正常,但作为一个组件,它没有.我以前做过组件没有问题,只是看不出这里的问题.如果我在组件代码中注释,并且指令输出,则它不起作用.

知道我做错了什么吗?

(function() {
"use strict";

angular
    .module('x.y.z')


    // .component('triangularStatus', {
    //     bindings: {
    //         value: '=',
    //         dimension: '=?'
    //     },
    //     templateUrl: '/path/to/triangular-status.html',
    //     controller: TriangularStatusController,
    //     controllerAs: 'vm'
    // });


    .directive('triangularStatus', triangularStatus);

    function triangularStatus() {
        var directive = {
            scope: {
                value: '=',
                dimension: '=?'
            },
            replace: true,
            templateUrl: '/path/to/triangular-status.html',
            controller: TriangularStatusController,
            controllerAs: 'vm',
        };
        return directive;
    }



    TriangularStatusController.$inject = [];
    function TriangularStatusController() {
        var vm = this;
    }
})();
Run Code Online (Sandbox Code Playgroud)

javascript web-component angularjs angular-directive angular-components

6
推荐指数
1
解决办法
7567
查看次数

Angular指令:可以测试某些字符在按键事件中是否被拒绝?

我一直在构建一个指令,限制用户按下某些无效字符,在这种情况下,使用keypress事件绑定到使用我的指令的输入元素.我一直在尝试测试这个功能,但我不明白如何实现这一点.

我的指示

angular
    .module('gp.rutValidator')
    .directive('gpRutValidator', directive);

  directive.$inject = ['$filter'];

  function directive($filter){
    var ddo = {
      restrict: 'A',
      require: 'ngModel',
      link: linkFn
    };
    return ddo;

    function linkFn(scope, element, attrs, ngModel){

      //valid characters are digits, dash and letter k
      var regexValidKeys = (/[\d\.\-k]/i);

      element.bind('keypress', function(e){

        var key = e.key || String.fromCharCode(e.keyCode);

        if (!regexValidKeys.test(key)) {
          e.preventDefault();
          return false;
        }

      });

    }
  }
Run Code Online (Sandbox Code Playgroud)

我的考试

describe('Angular Rut Validator Directive',validatorDirectiveSpec);

  function validatorDirectiveSpec(){

    //////////////  GLOBALS   ////////////////////////////////
    var scope, element, evt;
    //////////////  BEFORE EACH ////////////////////////////////
    beforeEach(module('gp.rutValidator')); …
Run Code Online (Sandbox Code Playgroud)

javascript testing jasmine angularjs angular-directive

6
推荐指数
1
解决办法
298
查看次数

Angular 4:未调用自定义验证程序

我已经为pan卡号验证定义了一个自定义验证器(https://en.wikipedia.org/wiki/Permanent_account_number).

function validatePan(): ValidatorFn {

 return (c: AbstractControl) => {   
            var regpan = /^([a-zA-Z]){5}([0-9]){4}([a-zA-Z]){1}?$/;

            if (!regpan.test(c.value)) {
                return {
                    validatepan: {
                      valid: false
                    }
                  };
            } else {
                return null;
            }
        }
}        

@Directive({
 selector: '[validatepan][ngModel], [validatepan][formControlName],    [validatepan][formControl]',
   providers: [
    { provide: NG_VALIDATORS, useExisting: forwardRef(() => PanValidator),     multi: true }
   ]
})
export class PanValidator implements Validator{
    validator: ValidatorFn;

  constructor() {
    this.validator = validatePan();
  }

  validate(c: FormControl) {
    console.log('here');
    return this.validator(c);
  }

}
Run Code Online (Sandbox Code Playgroud)

我已在模块的声明部分注册了该指令

 declarations: [
        ....
        PanValidator …
Run Code Online (Sandbox Code Playgroud)

validation angular-directive angular

6
推荐指数
2
解决办法
2934
查看次数

为什么此Angular验证指令显示为异步?

我想用模板形式[min][max]指令,所以我创造了他们和他们的工作.但测试让我感到困惑:验证不是异步执行的,但在更改了我的值和内容之后,我必须经历这个:

component.makeSomeChangeThatInvalidatesMyInput();
// control.invalid = false, expected

fixture.detectChanges();
// control.invalid is still false, not expected

// but if I go do this
fixture.whenStable().then(() => {
  // control.invalid is STILL false, not expected
  fixture.detectChanges();
  // control.invalid now true
  // expect(... .errors ... ) now passes
})
Run Code Online (Sandbox Code Playgroud)

我不明白为什么我甚至需要这个whenStable(),更不用说另一个detectChanges()循环了.我在这里错过了什么?为什么我需要2个周期的变化检测才能执行此验证?

如果我运行测试无关紧要async.

这是我的测试:

@Component({
    selector: 'test-cmp',
    template: `<form>
        <input [max]="maxValue" [(ngModel)]="numValue" name="numValue" #val="ngModel">
        <span class="error" *ngIf="val.invalid">Errors there.</span>
    </form>`
})
class TestMaxDirectiveComponent {
    maxValue: number; …
Run Code Online (Sandbox Code Playgroud)

validation angular-directive angular angular-test

6
推荐指数
1
解决办法
184
查看次数

角度测试错误 - NullInjectorError:没有TrimInputDirective的提供者

我创建了一个Angular Directive,它使用CSS选择器自动修剪我的应用程序中的输入,它看起来像......

import { Directive, HostListener, forwardRef } from '@angular/core';
import { DefaultValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';

export const TRIM_VALUE_ACCESSOR: any = {
  provide: NG_VALUE_ACCESSOR,
  useExisting: forwardRef(() => TrimInputDirective),
  multi: true
};

/**
 * The trim accessor for writing trimmed value and listening to changes that is
 * used by the {@link NgModel}, {@link FormControlDirective}, and
 * {@link FormControlName} directives.
 */
/* tslint:disable */
@Directive({
  selector: `
    input
    :not([type=checkbox])
    :not([type=radio])
    :not([type=password])
    :not([readonly])
    :not(.ng-trim-ignore)
    [formControlName],

    input
    :not([type=checkbox])
    :not([type=radio])
    :not([type=password])
    :not([readonly])
    :not(.ng-trim-ignore) …
Run Code Online (Sandbox Code Playgroud)

javascript unit-testing angular-directive angular angular-unit-test

6
推荐指数
1
解决办法
4131
查看次数

指定索引处的动态组件未正确放置

我试图在Angular中显示一个简单的项目列表,侧面有一个可点击的div; 在用户选择时,组件应在单击的组件下方动态创建新组件.

为此目的,我使用ComponentFactoryResolver没有相关问题; 但是,使用ViewContainerRefas parent,我无法找到如何将创建的组件放在指定的索引处,即使我将其指定为createComponent()方法中的参数也是如此.

app.component.html

<h3>Click on the arrow to create a component below the item clicked.</h3>

<div #myContainer>
  <div *ngFor="let thing of things; let index = index">
    <div class="inline click" (click)="thingSelected(thing, index)"> > </div>
    <div class="inline">{{thing.id}}</div>
    <div class="inline">{{thing.name}}</div>
    <div class="inline">{{thing.value}}</div>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

app.component.ts

export class AppComponent  {  
  @ViewChild('myContainer', { read: ViewContainerRef }) container: ViewContainerRef;

  things = [];
  constructor(private componentFactoryResolver: ComponentFactoryResolver){
    for(let i=0; i < 10; i++)
      this.things.push({id: i, name: "thing" + i, …
Run Code Online (Sandbox Code Playgroud)

typescript angular-directive angular

6
推荐指数
1
解决办法
284
查看次数