[英]angular directive not listening to changes in outer scope
I'm currently trying to get my directive to listen to changes happening to a specific variable in the parent scope. 我目前正试图让我的指令听取父作用域中特定变量发生的变化。 For that purpose I came up with the following code which runs fine the first time the controller gets loaded but is not picking up the change to the variable gridCells in the second part running in the $timeout.
为此,我提出了以下代码,该代码在第一次加载控制器时运行良好,但是没有在$ timeout中运行的第二部分中获取对变量gridCells的更改。
Anyone able to give me a hint what I'm doing wrong here? 有人能给我一个提示我在这里做错了吗?
Controller: 控制器:
$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: HTML:
<my-directive cells=gridCells></my-directive>
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}}'
};
}]);
You need to use $watchCollection
instead of $watch
or do a deepWatch ( scope.$watch(prop, func, true)
) in order to be able to track the changes in the array that has been 2-way bound. 您需要使用
$watchCollection
而不是$watch
或执行deepWatch( scope.$watch(prop, func, true)
),以便能够跟踪已经双向绑定的数组中的更改。 It is also better to watch scope property cells
instead of attribute cells
观察范围属性
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]);
}
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.