使用$ watch来处理复选框数组中的更改.不行

Ily*_*bin 3 angularjs angularjs-scope

我有三个复选框

<span class="checkbox-label clicks-label"><input type="checkbox" ng-model="checkboxes[0]">Clicks <span class="glyphicon glyphicon-question-sign"></span> </span>
            <span class="checkbox-label views-label"><input type="checkbox" ng-model="checkboxes[1]">Views <span class="glyphicon glyphicon-question-sign"></span> </span>
            <span class="checkbox-label ctr-label"><input type="checkbox" ng-model="checkboxes[2]">Click-Trough Rate <span class="glyphicon glyphicon-question-sign"></span> </span>
Run Code Online (Sandbox Code Playgroud)

而这个代码在控制器中

$scope.checkboxes = [true,true,true];


$scope.$watch('checkboxes', function(newValue, oldValue){
            debugger
        });
Run Code Online (Sandbox Code Playgroud)

我希望在其中一个复选框更改值时运行某些方案.

但是当我更改值时,我没有到达调试器.有任何想法吗?做正确的方法是什么?谢谢

PSL*_*PSL 6

由于您正在使用数组,因此您需要使用deep watch($scope.$watch('expn', fn, true))或$watchCollection(专门用于观看集合但未深入观看).另请注意,您可以将ng-change事件绑定到这些复选框,并避免添加任何观察者(您可以在此处找到这些行的答案).

尝试:

$scope.$watchCollection('checkboxes', function(newValue, oldValue) {
  console.log(newValue);
});
Run Code Online (Sandbox Code Playgroud)

另外,不要重复视图中的复选框,您可以使用对象数组创建更好的视图模型,甚至包括复选框名称等,并将其与ng-change事件绑定.

angular.module('app', []).controller('ctrl', function($scope) {
  $scope.checkboxes = [true, true, true];


  $scope.$watchCollection('checkboxes', function(newValue, oldValue) {
    console.log(newValue);
  });
})
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
  <span class="checkbox-label clicks-label"><input type="checkbox" ng-model="checkboxes[0]">Clicks <span class="glyphicon glyphicon-question-sign"></span> </span>
  <span class="checkbox-label views-label"><input type="checkbox" ng-model="checkboxes[1]">Views <span class="glyphicon glyphicon-question-sign"></span> </span>
  <span class="checkbox-label ctr-label"><input type="checkbox" ng-model="checkboxes[2]">Click-Trough Rate <span class="glyphicon glyphicon-question-sign"></span> </span>
</div>
Run Code Online (Sandbox Code Playgroud)