2014-10-08 51 views
1

我目前正试图让我的指令来监听发生在父范围内的特定变量的变化。为此,我提出了以下代码,它在第一次加载控制器时运行正常,但不会在$ 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}}' 
    }; 
}]); 

回答

3

您需要使用$watchCollection代替$watch或做deepWatch(scope.$watch(prop, func, true)),以便为能够跟踪有蜜蜂的阵列中的变化双向绑定。这也是更好地观看scope属性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

+0

这解决了这个问题,非常感谢。 – jimmy 2014-10-08 23:45:10

+0

@jimmy酷..不客气.. :) – PSL 2014-10-08 23:45:24