0

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?

2 Answers 2

2

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
}
Sign up to request clarification or add additional context in comments.

Comments

0

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);

1 Comment

Please add some context to your answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.