angularjs - 使用 $watch 来处理复选框数组中的更改。不起作用

标签 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>

Controller 中的这段代码

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


$scope.$watch('checkboxes', function(newValue, oldValue){
            debugger
        });

我想在其中一个复选框更改值时运行一些场景。

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

最佳答案

由于您正在使用数组,因此您需要使用 deep watch ($scope.$watch('expn', fn, true)) 或 $watchCollection (专门设计用于观看收藏但不被深度观看)。另请注意,您可以将 ng-change 事件绑定(bind)到这些复选框并避免添加任何观察者(这些行的答案 you can find here )。

尝试:

$scope.$watchCollection('checkboxes', function(newValue, oldValue) {
  console.log(newValue);
});

换句话说,与其在 View 中重复复选框,不如创建一个更好的 View 模型,其中包含对象数组,甚至包括复选框名称等,并将其与 ng-change 事件绑定(bind)。

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


  $scope.$watchCollection('checkboxes', function(newValue, oldValue) {
    console.log(newValue);
  });
})
<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>

关于angularjs - 使用 $watch 来处理复选框数组中的更改。不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28001377/

相关文章:

jquery - MaterializeCSS 动态添加自动完成字段

javascript - Angular 错误 : [ng:area] and [$injector:unpr] when import ngUpload

javascript - 如何简化此 switch 语句(Angular 应用程序)

angularjs - 没有模板的 Angular 组件表达式绑定(bind)

Angular js : cannot call method from list comprehension in select

angularjs - 在字典(对象)中使用ng-options进行迭代

javascript - 如何在使用 AngularJS 提交 <select> 时绑定(bind)、填充和获取选定值

angularjs - 在 ng Select 中设置默认值

angularjs - Angular 1.2 和 Angular 1.6 之间触发 ng-click 和 ng-change 的顺序差异

javascript - 如何制作一个 Angular js函数来多次更改按钮内容