我无法理解以下行为:
这是我的角度代码:
(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/