2014-10-08 92 views
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}}' 
    }; 
}]); 

回答

3

您需要使用$watchCollection代替$watch或做deepWatch(scope.$watch(prop, func, true)),以便爲能夠跟蹤有蜜蜂的陣列中的變化雙向綁定。這也是更好地觀看scope屬性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]); 
    } 
    } 
}); 

Plnkr

+0

這解決了這個問題,非常感謝。 – jimmy 2014-10-08 23:45:10

+0

@jimmy酷..不客氣.. :) – PSL 2014-10-08 23:45:24