我相信这将是其中之一" duh"事情,但我似乎无法弄清楚为什么我的指令在我的指令中解雇。
我有一个指令,要写出有问题的项目。我试图通过
来引用该项目scope: {
item: '=criteriaDescription'
}
以及使用$ parse,所以我不必有一个孤立的范围,似乎都没有工作,因为我改变了'代码aint被调用。这是我的指示
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>
答案 0 :(得分:2)
您不需要解析。
试试这个..
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);
这将在链接功能开始时进行评估。
由于此值仅评估一次,因此不会更改。
因此,你的手表不会被解雇。
答案 1 :(得分:1)
由于范围已被隔离,您可以使用scope.items
访问权限,并使用$watchCollection
注意更改:
angular.module('app').directive('criteriaDescription', [function () {
'use strict';
return {
scope: {
item: '=criteriaDescription'
},
link: function (scope, element, attrs) {
scope.$watchCollection('item', function (newValue, oldValue) {
var desc = 'You have a name of ' + newValue.name;
element.html(desc);
});
}
};
}]);
演示: http://plnkr.co/edit/hSrRyKM8LQbp5evbaywD?p=preview
您还可以将$watch
与第三个参数true
一起使用,以强制进行深层对象比较以检测更改:
scope.$watch('item', function (newValue, oldValue) {
var desc = 'You have a name of ' + newValue.name;
element.html(desc);
}, true);
答案 2 :(得分:0)
为什么需要自定义指令?你不能这样做吗?
<tr ng-repeat="item in report.criteria">
<td>
<h5 ng-bind="item.name"></h5>
<span>You have a name of {{item.name}}</span>
</td>
</tr>