我使用 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="">
最佳答案
重建整个指令是可行的,但这是一种强力解决方案 - 对于像这样接受用户输入的指令来说尤其不可取,如果您重新初始化该指令,这些指令将会被破坏。
相反,您可以使用 scope.$watch
或 attrs.$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
});
}
}
});
AngularJS : Difference between the $observe and $watch methods对 $observe 和 $watch 之间的差异有很好的解释。
关于angularjs - 如何重新初始化 Angular 指令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36264231/