2015-09-28 72 views
2

我想了解$ watch如何通過示例工作,但不工作。在這個例子中,我正在觀看一個名爲收藏夾的數組,該數組位於$範圍內。如果收藏夾數組發生變化,我希望在控制檯中寫入新值。不知道這是否是使用$ watch的正確方法。

控制器代碼

var mods = angular.module("listApp",[]) 
    mods.controller("prodCtlr", function($scope){ 
      $scope.favorites = ["a", "b", "c", "d"]  

      $scope.delete = function(index){ 
       $scope.favorites.splice(index,1) 
      } 

      $scope.$watch(function(){ 
       return $scope.favorites; 
      }, function(newVal, oldVal){ 

       console.log(newVal); 

      }) 

     } 
    ); 

HTML

 <table class="table table-striped"> 
      <tr ng-repeat="fav in favorites"> 
      <td>{{fav}}</td><td><input type="button" class="btn btn-primary" value="Delete!" ng-click="delete($index)" ng-model="fav"></input></td> 
      </tr> 
     </table> 

回答

3

使用$watchCollection

$scope.favorites = ["a", "b", "c", "d"]; 
$scope.dataCount = 4; 

$scope.$watchCollection('favorites', function(newFavs, oldFavs) { 
    $scope.dataCount = newFavs.length; 
}); 
+0

輝煌,適合我!謝謝。 – tintin

0

您也可以用深的手錶上使用,如:

$scope.$watch('favorites', function(newFavs, oldFavs) { 
    $scope.dataCount = newFavs.length; 
}, true); 

$腕錶()將被觸發:

$scope.myArray = []; 
$scope.myArray = null; 
$scope.myArray = someOtherArray; 

$ watchCollection()將通過一切上方,​​觸發:

$scope.myArray.push({}); // add element 
$scope.myArray.splice(0, 1); // remove element 
$scope.myArray[0] = {}; // assign index to different value 

$腕錶(...,TRUE)將被觸發通過上面的一切AND:

$scope.myArray[0].someProperty = "someValue"; 

其他注意:$ watch(...,true)將不會被觸發時,監測對象被重建。 $ watchCollection(...,true)將在重建時觸發。