如何重新初始化Angular指令?

Mr *_*ith 5 angularjs angularjs-directive

我正在使用fcsaNumber指令检查输入到输入框中的数字的有效性.我得到了这个工作,但我检查的值是动态的,这意味着它可以根据选择的选项而改变.看来这个指令只初始化一次.当选项发生变化时,我需要做些什么来重新初始化?

//this works fine
    <input name="Employees" type="text" ng-model="Input.Employees" fcsa-number="{min: 1}" required="">

//this only inits once, so its not dynamic
    <input name="Employees" type="text" ng-model="Input.Employees" fcsa-number="{{getMin()}}" required="">
Run Code Online (Sandbox Code Playgroud)

Dan*_*eck 7

重建整个指令会起作用,但它是一个强力解决方案 - 对于像这样接受用户输入的指令尤其不受欢迎,如果你重新启动指令就会被吹走.

相反,您可以使用scope.$watchattrs.$observe允许指令更容易地响应其属性值的更改:

module.directive('foo', function() {
    return {
        scope: {
            'bar': '@'
        },
        link: function(scope, element, attrs) {
            scope.$watch('bar', function() {
                // runs when scoped value 'bar' changes
            });
            attrs.$observe('baz', function() {
                // Similar to $watch, but without isolate scope
            });
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

AngularJS:$ observe和$ watch方法之间的差异很好地解释了$ observe和$ watch之间的差异.


Ale*_*son 6

您可能会使用ng-if初始化/拆除相关指令.(ng-if docs)

ngIf指令根据表达式删除或重新创建DOM树的一部分.如果分配给ngIf的表达式求值为false值,则从DOM中删除该元素,否则将元素的克隆重新插入DOM中 - CodeHater

这是一个伟大的堆栈溢出的答案对之间的差异ng-ifng-show.