0

我无法理解以下行为:

这是我的角度代码:

(function(){
'use strict';
angular.module('myMod',[ ])
    .controller('abc',function($scope) {
        $scope.products = products;

        $scope.printProducts = function(){
            for(var index in $scope.products){
              console.log($scope.products[index].key + " " + $scope.products[index].check);
            }
        };

    });

   var products = [{key:'HERO',check:0}, {key:'MARUTI',check:0}, {key:'TATA',check:0}]; 
   }());

这是我的 HTML:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Test</title>
</head>
<body ng-app="myMod">
    <div ng-controller="abc">
       <div ng-repeat="product in products">
        <label><input type="checkbox" ng-true-value='1' ng-false-value='0' ng-model='product.check' ng-click="printProducts()">{{product.key}}{{product.check}}</label>
      </div>
    </div>  
<!-- scripts section -->
<script type="text/javascript" src = "angular.js"></script>
<script type="text/javascript" src= "basic.js"></script>
</body>
</html>

So here I am trying to bind to a property of an object 'check' in this case to the output of my checkbox which when selected returns 1 and when unselected gives a value of 0. However, when I am printing the property in console inside for 循环我得到了意想不到的行为。

例如:当我选择“HERO”时,我得到了这个输出: HERO 0 --> 这里应该是 1 MARUTI 0 TATA 0

现在,当我选择 Maruti 时,我得到: HERO 1 MARUTI 0 --> 这里应该是 1 TATA 0

谁能解释一下这里发生了什么?链接到小提琴(以为你看不到控制台输出)http://jsfiddle.net/k2wfyj6e/

4

1 回答 1

1

您需要使用ng-change而不是ng-click. ng-click(基本上是下面的点击事件)发生得太早, change事件仅在此之后触发。Angular 监听 change 事件来更新模型值。所以听ng-click会为时过早,因为 Angular 还没有处理和设置模型。

所以尝试: -

   <input type="checkbox" ng-true-value='1' ng-false-value='0' 
          ng-model='product.check' ng-change="printProducts()">
         {{product.key}}{{product.check}}</label>

演示

于 2015-01-03T00:39:15.220 回答