在嵌套数据更改后,ng-repeat不会更新

时间:2014-10-27 14:02:10

标签: javascript angularjs d3.js angularjs-directive angularjs-ng-repeat

我有一个使用d3.js绘制内容的指令,如果我绘制它取决于我的范围中的数据。我的问题是我无法在更改后重新绘制内容,我尝试了使用$ scope的变体。$ apply并且到目前为止还没有取得任何成功。

HTML:

<body ng-app="App" ng-controller="Mainctrl">
  <div ng-repeat="val in data">
    <div draw="" value="{{val.avg}}">{{val.avg}}</div>
  </div>
</body>

JS:

var app = angular.module('App', []);
app.controller('Mainctrl', function ($scope, $timeout) {
  $scope.data = 
  [{avg: 0},
  {avg: 1}];

  $timeout(function (){
    var i = 1;
      for (key in $scope.data){
         $scope.data[key].avg = i++; 
      };
    }
    ,3000)
  });

  app.directive('draw', function() {
    return {
      scope: {
        value: "@"
    },
    link: function (scope, element, attrs){
      if (attrs.value != 0) {
      var svgContainer = d3.select(element[0]).append("svg").attr("width", 200).attr("height", 200);
      var circle = svgContainer.append("circle").attr("cx", 30).attr("cy", 30).attr("r", 20);
      }
    }
  }

 });

这是一个重复问题的傻瓜:http://plnkr.co/edit/V62WngzpmsBWh6zSHCcM

1 个答案:

答案 0 :(得分:2)

将您的指令更改为:

 app.directive('draw', function() {
    return {
       scope: {
       value: "=" //<---
    },
  link: function (scope, element, attrs){
     scope.$watch("value", function(val) {
        //draw stuff with val
     });
  }
}

}

和你的html:

<body ng-app="App" ng-controller="Mainctrl">
   <div ng-repeat="val in data">
     <div draw value="val.avg">{{val.avg}}</div>
  </div>
</body>

这是更新的plunkr:http://plnkr.co/edit/pIN8iy77QY5n4THqIcLp?p=preview