user2428183
user2428183

Reputation: 43

AngularJs $watch issue

in my application i have a controller and a directive which i use to draw a chart. so my model is like this: $scope.d3DataGraph ={"selected":{"node":"","impiega":[],"impiegato": []} , "nodes":[],"links":[]};

in the controller i've set up a function that adds some data to the model:

 $scope.d3DataGraph.nodes.push(articolo);

then i have the directive which is responsible to draw the graph by adding some svg tags to the dom:

in my directive i have a render function that have to be triggered when the model changed...

 angular.module('myApp.directives')
.directive('d3Graph', ['d3', function(d3) {
  return {
    restrict: 'EA',
    scope: {
      data: "=",
      query: "=",
      label: "@",
      onClick: "&"
    },
    link: function(scope, iElement, iAttrs) {

      var svg = d3.select(iElement[0]).append("svg")
        .attr("width", "100%")
        .attr("height", "800px");
       var datatree = {};

        scope.$watch(function(){ return scope.data.nodes; }, function(){
            return scope.render(scope.data, scope.query);
          }
        );

      scope.render = function(datatreex, query){....

the directive is "called" whit this tag

<d3-graph data="d3DataGraph" selected = "selected" query = "selezionati"></d3-graph>

the problem is that the render function is called only when the page is loaded, but not when the controller updates the model ...

where i get wrong? the overall set up seems to be correct, what do you think of it?

Upvotes: 1

Views: 72

Answers (1)

hjl
hjl

Reputation: 2802

That's because $watch is just watching the reference of scope.data.nodes, so no matter what you push or pop, the reference will not change.

Instead of using $watch, you can use $watchCollection. It will detect the length of the array.

scope.$watchCollection('data.nodes', function(){
    return scope.render(scope.data, scope.query);
});

Upvotes: 1

Related Questions