问题
Basically I have a custom directive which has an isolated scope. I two-way bind a piece of data and given those data, I generate some output. For example, the data is two numbers 1 and 3. In the link() function of the directive I create a new array generating a sequential number between the two numbers. That new array I set in the scope. In the template, I do an ng-repeat on that new array. If I change those two numbers, the template does not seem to pick up the change. Here is a jsfiddle sample of what I am talking about:
http://jsfiddle.net/m2jf1Lw7/1/
You can see that when you click on change, nothing happens. If you change the template for my directive to be:
template: '<ul><li ng-repeat="d in data.list" my-button="d"></li></ul>'
changing "pages" to "data.list". If you click on change, you can see that the list will now change properly.
I am new to angularjs. I looked to see if there was a question similar to mine, but couldn't find any. My apologies if this is formatted or done incorrectly. Thanks for any insight.
回答1:
As Nikos said, if you really want to detect the change of all the properties of the data
variable, you need to use deep watch
as following:
...
link: function (scope, element, attrs) {
scope.$watch(function () {
return scope.data
}, function () {
var pages = [];
for (var i = scope.data.list[0]; i <= scope.data.list[1]; i++) {
pages.push(i);
}
scope.pages = pages;
}, true); // The third parameter is true for deep watch
},
...
JSFiddle.
回答2:
The '='
scope binding creates a watch on the variable you pass to it, in your case the data
. So any change in the data
triggers the watch and updates the isolated scope.
Watches on objects are by default using the equality, not deep watch: if the object reference remains the same, it is not considered changed, disregarding what happened to its contents. In your case you are changing the contents of data
, but not the reference to data
itself.
Same for data.list
: When you watch data.list
and then set $scope.data.list
to a different value, the reference changes and the watch is triggered.
来源:https://stackoverflow.com/questions/28601772/why-does-my-custom-directive-not-update-when-i-derive-the-output-from-the-bounde