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