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.
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:
<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. It is also better to watch scope property cells
instead of attribute 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]);
}
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.