angular指令不听外部范围的变化

时间:2014-10-08 23:13:59

标签: angularjs angularjs-directive angularjs-scope

我目前正试图让我的指令听取父范围内特定变量发生的变化。为此我想出了以下代码,它在第一次加载控制器时运行良好,但是没有在$ timeout中运行的第二部分中获取对变量gridCells的更改。

任何人都能给我一个提示我在这里做错了什么吗?

控制器:

$scope.gridCells = [];
$scope.gridCells.push({value: '1'});
$scope.gridCells.push({value: '2'});
$scope.gridCells.push({value: '1'});
$scope.gridCells.push({value: '2'});

// this change is not reflected in the directive
$timeout(function() {
  console.log('push');
  $scope.gridCells.push({value: '2'});
  $scope.gridCells.push({value: '1'});
}, 4000);

HTML:

<my-directive cells=gridCells></my-directive>

指令:

angular.module('myApp').directive('myDirective', [ function() {
  return {
    restrict: 'E',
    scope: {
      cells: '='
    },
    link: function (scope, element, attrs) {

      scope.gridCells = [];

      scope.$watch(attrs.cells, function(newValue, oldValue) {

        console.log('new: ' + newValue);
        console.log('old: ' + oldValue);

        for(var i = 0; i < scope.cells.length; i++) {
          // populate my scope.gridCells variable with some of the content in the UPDATED cells variable
          if (scope.cells[i].value === '1') {
            gridCells.push(scope.cells[i]);
          }

        }

      });

    },
    template: '{{gridCells.length}}'
  };
}]);

1 个答案:

答案 0 :(得分:3)

您需要使用$watchCollection代替$watch或执行deepWatch(scope.$watch(prop, func, true)),以便能够跟踪已经双向绑定的数组中的更改。观看范围属性cells而不是属性cells

也更好
scope.$watchCollection('cells', function() {
 //probably you want to reset gridCells here?
  //scope.gridCells = [];
  for(var i = 0; i < scope.cells.length; i++) {
     if (scope.cells[i].value === '1') {
      scope.gridCells.push(scope.cells[i]);
   }
  }
});

<强> Plnkr