AngularJs $观看问题

AngularJs $watch issue

在我的应用程序中,我有一个控制器和一个用于绘制图表的指令。 所以我的模型是这样的:$scope.d3DataGraph ={"selected":{"node":"","impiega":[],"impiegato": []} , "nodes":[],"links":[]};

在控制器中,我设置了一个向模型添加一些数据的函数:

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

然后我有指令负责通过向 dom 添加一些 svg 标签来绘制图形:

在我的指令中,我有一个必须在模型更改时触发的渲染函数...

 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){....

指令是 "called" 这个标签

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

问题是渲染函数只在页面加载时调用,控制器更新模型时不调用...

我哪里错了? 整体设置似乎是正确的,你觉得怎么样?

那是因为$watch只是在看scope.data.nodes的引用,所以无论你push还是pop,引用都不会改变。

您可以使用 $watchCollection 而不是 $watch。它将检测数组的长度。

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