我试图通过一个例子来理解 $watch 是如何工作的,但它不起作用。在示例中,我正在观看一个名为 favorites 的数组,该数组位于 $scope 内。如果收藏夹数组发生变化,我希望在控制台中写入新值。不确定这是否是使用 $watch 的正确方法。
Controller 代码
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>
最佳答案
使用$watchCollection :
$scope.favorites = ["a", "b", "c", "d"];
$scope.dataCount = 4;
$scope.$watchCollection('favorites', function(newFavs, oldFavs) {
$scope.dataCount = newFavs.length;
});
关于angularjs - 了解 $watch 的工作原理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32830323/