我有三个复选框
<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/