Reputation: 13321
I'm using AngularJS 1.2
I'm passing an array via ng-model
into a custom directive.
The data is in the directive when it is loaded, but when changes are made to the model in the main controller, the model in the directive isn't updating.
This is the relative partial my controller uses. (not the directive controller) ui.pct
is an array of percentages.
<dprogress ng-model="ui.pct"></dprogress>
Here's the directive: ``` angular.module('dprogress', []) .directive('dprogress', function () {
function makeChart(data) {
var chart = d3.select('#chart')
.append("div").attr("class", "chart")
.selectAll('div')
.data(data)
.enter()
.append("div")
.style("width", function(d) { return d + "%"; })
.text(function(d) { return d + "%"; });
}
return {
restrict: 'E',
scope: { data: "=ngModel" },
template: '<div id="chart"></div>',
link: function (scope, element, attrs) {
makeChart(scope.data);
}
};
}); ```
I've added scope.$watch('data')
in the link, but it would not trigger when the data was being changed from outside the directive.
How can I update the data in my directive when it is changed from outside?
Upvotes: 0
Views: 2128
Reputation: 3464
When objectEquality == true, inequality of the watchExpression is determined according to the angular.equals function. To save the value of the object for later comparison, the angular.copy function is used. This therefore means that watching complex objects will have adverse memory and performance implications.
scope.$watch('data', yourCallback, true);
Upvotes: 0
Reputation: 3162
Your data is probably an array and you need to deepwatch it. A simple watch will check if the reference is changed bu no the content.
link: function (scope, element, attrs) {
makeChart(scope.data);
scope.$watch('data', makeChart, true); // last arg is for deepwatch
}
Upvotes: 2