我确信这将是那些“废话”的事情之一,但我似乎无法弄清楚为什么我的 watch 在我的指令中触发。
我有一个指令,要写出一些关于有问题的项目。我试图通过
引用该项目scope: {
item: '=criteriaDescription'
}
以及使用 $parse,所以我不必有一个独立的范围,两者似乎都不起作用,因为我的“更改”代码没有被调用。这是我的指令
angular.module('app').directive('criteriaDescription', ['$parse', function ($parse) {
'use strict';
return {
restrict: 'A',
link: function (scope, element, attrs) {
var item = $parse(attrs.criteriaDescription)(scope);
// generate a description for this criteria item, based on values and options
scope.$watch(function () {
return item;
}, function (newValue, oldValue) {
var desc = 'You have a name of ' + newValue.name;
element.html(desc);
});
}
};
}]);
我使用该指令的 HTML 看起来像这样,正如您所看到的,我在指令之外显示了名称,并且当我更改它时它会更新。
<tr ng-repeat="item in report.criteria">
<td>
<h5 ng-bind="item.name"></h5>
<span criteria-description="item"></span>
</td>
</tr>
最佳答案
你不需要解析。
试试这个..
scope.$watch(attrs.criteriaDescription, function (newValue, oldValue) {
var desc = 'You have a name of ' + newValue.name;
element.html(desc);
}, true);
在您提供的代码片段中,
var item = $parse(attrs.criteriaDescription)(scope);
这将在链接功能开始时进行评估。
因为这个值只计算一次,所以它不会改变。
因此您的 watch 不会被触发。
关于javascript - Angular : Why is my watch not firing?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28762645/