[英]Undetected change on angular directive attribute
I'm facing a problem with angular directive. 我遇到了角度指令的问题。
I want a directive to "change itself" depending on a attribute. 我希望指令根据属性“自行更改”。 Unfortunatly, the watcher on The attribute never claim change. 不幸的是,“属性”上的观察者从未声明过更改。
Here is a fiddle JS Which explain my situation : http://jsfiddle.net/gmjm84m1/ (whenever you change 'something',the watch do not react, if you inspect 'here', you can see that the content attribute as change...) 这是一个小提琴JS,它解释了我的情况: http : //jsfiddle.net/gmjm84m1/ (无论您何时更改“某物”,手表都不会做出反应,如果您检查“此处”,则可以看到content属性已更改) ...)
HTML 的HTML
<div ng-app="myDirective" ng-controller="x">
<div content="{{something}}" my-directive>
<p>here</p>
</div>
<p>{{something}}</p>
<input type="text" ng-model="something"></p>
JS : JS:
angular.module('myDirective', []).directive('myDirective', function () {
return {
restrict: 'A',
link: function (scope, element, attrs) {
scope.$watch(attrs.content, function (v) {
console.log('value changed, new value is: ' + v);
});
}
};
});
function x($scope) {
$scope.something = "yolo";
}
Can Somebody tell me why ? 有人可以告诉我为什么吗? Maybe it's the wrong way ? 也许这是错误的方式?
Bad way to fix: 不好的解决方法:
restrict: 'A',
link: function (scope, element, attrs) {
scope.$watch(function () { return attrs.content }, function (v) {
console.log('value changed, new value is: ' + v);
});
}
Good way to fix: 修复的好方法:
restrict: 'A',
scope: {
content: '@'
},
link: function (scope, element, attrs) {
scope.$watch('content', function (v) {
console.log('value changed, new value is: ' + v);
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.