您要做的是监视指令中属性的属性。您可以使用 $observe() 观察属性变化的属性,如下所示:
angular.module('myApp').directive('conversation', function() {
return {
restrict: 'E',
replace: true,
compile: function(tElement, attr) {
attr.$observe('typeId', function(data) {
console.log("Updated data ", data);
}, true);
}
};
});
请记住,我在这里的指令中使用了“编译”功能,因为您没有提到您是否有任何模型以及这是否对性能敏感。
如果您有模型,则需要将 'compile' 功能更改为 'link' 或使用 'controller' 并监控模型的属性发生变化,您应该使用 $watch(),并从属性中取出角 {{}} 括号,例如:
<conversation style="height:300px" type="convo" type-id="some_prop"></conversation>
在指令中:
angular.module('myApp').directive('conversation', function() {
return {
scope: {
typeId: '=',
},
link: function(scope, elm, attr) {
scope.$watch('typeId', function(newValue, oldValue) {
if (newValue !== oldValue) {
// You actions here
console.log("I got the new value! ", newValue);
}
}, true);
}
};
});