此示例记录每个用户点击次数。复选框显示年龄/名称。单击复选框时,我希望更新计数器。单击年龄或名称时,我还希望更新计数器。
复选框ng-click
函数是$digest
迭代出现问题的地方。如果我从此函数中删除了$scope.counter ++
,它可以正常工作。 line 32 of app.js
我认为这种情况正在发生,因为$ scope.counter导致了一个新的摘要周期,导致$ scope.clicked函数被调用,依此类推。但是,我无法想到我应该如何做到这一点只增加一次。
您可以在此处找到示例: http://plnkr.co/edit/sk6lwj?p=info
我也会在这里发布代码。
<p>Click Count: {{clickCount}}.</p>
<table>
<tbody>
<tr>
<td></td>
<td>Name</td>
<td>Age</td>
</tr>
<tr ng-repeat="row in testData">
<td>
<label class="checkbox">
<input type="checkbox" ng-model="row.check" ng-checked="clicked(row)" />
</label>
</td>
<td>
<span ng-show="row.show" class="reason-show-hide" ng-click="nameClicked(row.name)">{{row.name}}</span>
</td>
<td>
<span ng-show="row.show" class="reason-show-hide" ng-click="ageClicked(row.age)">{{row.age}}</span>
</td>
</tr>
</tbody>
</table>
JS
var testData = [{
name: 'Moe',
age: 22,
show: false
}, {
name: 'Curly',
age: 23,
show: false
}, {
name: 'Shemp',
age: 20,
show: false
}];
var app = angular.module('plunker', ['ngAnimate']);
app.value('testData', testData);
app.controller('MainCtrl', function($scope, testData) {
var initialLoad = true;
$scope.name = 'World';
$scope.clickCount = 0;
$scope.testData = testData;
$scope.clicked = function(row) {
if (row.check === true)
row.show = true;
else
row.show = false;
// this line causes the $digest loop
$scope.clickCount++;
console.log("Click Count updated by:" + row.name + " checkbox");
};
initialLoad = false;
$scope.nameClicked = function(msg) {
$scope.clickCount++;
console.log("Click count updated by:" + msg + " name clicked");
};
$scope.ageClicked = function(msg) {
$scope.clickCount++;
console.log("Click count updated by:" + msg + " aged clicked");
};
$scope.shouldShow = function(row) {
return row.show;
};
});
答案 0 :(得分:0)
那么,
问题出在第33行,你有:
<input type="checkbox" ng-model="row.check" ng-checked="clicked(row)" />
但我认为应该是
<input type="checkbox" ng-model="row.check" ng-click="clicked(row)" />
ng-checked
是checked
属性的Angular指令,而不是用于设置/取消设置复选框的事件处理程序,因此Angular在循环中调用和评估它。
只有这一项改变才有效: