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}}'
};
}]);
这解决了这个问题,非常感谢。 – jimmy 2014-10-08 23:45:10
@jimmy酷..不客气.. :) – PSL 2014-10-08 23:45:24