![](/img/trans.png)
[英]Angular - listening to binding changes in directive executed by controller
[英]angular directive not listening to changes in outer 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}}'
};
}]);
您需要使用$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]);
}
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.