切换复选框时,ng-model上的watchCollection不会触发

时间:2016-11-04 06:23:01

标签: angularjs

单击复选框后,$scope.$watchCollection('classes'不会触发。有什么建议?

  <div class="filter-column">
    <div class="filter-title">Class</div>
    <div class="bottom-line"></div>
    <div class="overflow-container">
      <div ng-repeat="class in classes | orderBy">
        <input type="checkbox"
          ng-model="class.checked" >
        {{class.description}}
      </div>
    </div>
  </div>
$scope.$watchCollection('classes', function(newValue) {
  console.log('sss')
});

3 个答案:

答案 0 :(得分:1)

在这种情况下你可以有一个深度计,

$scope.$watch(function($scope) {
      return $scope.classes.
      map(function(obj) {
        return obj.checked
      });
    }, function(newVal) {
      $scope.checked = true;
      alert("css chagned");
    }, true);

DEMO

答案 1 :(得分:1)

&#13;
&#13;
// Code goes here

angular
  .module('myApp', [])

.controller('testController', ['$scope',
  function($scope) {

    $scope.classes = [{
      description: 'label1',
    }, {
      description: 'label2',
    }];

    $scope.$watch('classes', function(newValue) {
      console.log("watcher called");
    }, true);

  }
]);
&#13;
<!DOCTYPE html>
<html data-ng-app="myApp">

<head>
  <link rel="stylesheet" href="style.css">
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
  <script src="script.js"></script>
</head>

<body data-ng-controller="testController">

  <div class="filter-column">
    <div class="filter-title">Class</div>
    <div class="bottom-line"></div>
    <div class="overflow-container">
      <div ng-repeat="class in classes | orderBy">
        <input type="checkbox" ng-model="class.checked" ng-change="call(class)">{{class.description}}
      </div>
    </div>
  </div>

</body>

</html>
&#13;
&#13;
&#13;

$ watch能够获得更改。

答案 2 :(得分:1)

要修复您的代码,请按@Sajeetharan的回答进行深度收集。但我认为应该在你的情况下使用ng-change来捕获事件

<input type="checkbox" ng-model="class.checked" ng-change="chkChecked(class);"> {{class.description}}