简体   繁体   English

AngularJS:数组和深层的$ watch不起作用

[英]AngularJS: Array and deep $watch doesn't work

I have an array with boolean values and what I need to do is try to use the $watch function in order to show a message when some change happens in the array. 我有一个带有布尔值的数组,我需要做的是尝试使用$ watch函数,以便在数组中发生某些更改时显示一条消息。

As you can see in this code the array changes its values but the $watch function doesn't work. 如您在此代码中所见,数组更改了其值,但$ watch函数不起作用。 Any idea? 任何想法?

View 视图

<div data-ng-repeat="catA in categoryA">
    <b><input type="checkbox" checked="checked" ng-model="arrayCategoryA[$index]"/>{{catA.name}}</b>
</div>

Controller 控制者

app.controller("controllerApp", function($scope, $http, $filter){

  $scope.arrayCategoryA = [];

  $scope.$watchCollection($scope.arrayCategoryA, function(newVal, oldVal){
    console.log("something changed");
  }, true);

  $http.get("categoryA.json").success(function(data) {
     $scope.categoryA = data;
     for (var i = 0; i < $scope.categoryA.length; i++) 
     $scope.arrayCategoryA[i] = true;
  });

});

$watchCollection takes a watch expression and in this case is the name of the scope variable of arrayCategoryA . $watchCollection一个监视表达式,在这种情况下,它是arrayCategoryA的作用域变量的arrayCategoryA

 $scope.$watchCollection(`arrayCategoryA`, function(newVal, oldVal){
    console.log("something changed");
  }, true);

Updated working plunkr 更新了工作插件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM