AngularJS:计数,而在嵌套NG重复迭代 [英] AngularJS: Count while iterating in nested ng-repeat
问题描述
我已经创建了一个应用程序angularjs打印印度人民算作以及那些谁拥有投票资格的计数值,
I have created an angularjs application for printing the Indian people count as well as those who have vote eligible count values,
应用程序工作正常,但我不知道如何让印度人和投票资格,而计数迭代
The application is working fine but i dont know how to get indians and vote eligible counts while iterating
Working Demo
<div ng-app='myApp' ng-controller="Controller">
<div ng-init="indiansCount = 0" ng-repeat="emp in records">
<b>Can Vote :</b><br>
<b>Indians :</b> {{getIndiansCount(emp.country, indiansCount)}}
<div ng-repeat="empl in emp">
{{empl.country}}<br>
{{empl.employee.name}}<br>
{{empl.employee.canVote}}
<hr>
</div>
</div>
</div>
谁能告诉我一些建议该
Can anyone please tell me some suggestion for this
推荐答案
您 emp.country
是未定义
,因为 EMP
是员工的集合。你可以这样做,而不是:
Your emp.country
is undefined
, because emp
is a collection of employees. You could do this instead:
HTML
<b>Indians :</b> {{getIndiansCount(emp, indiansCount)}}
JS:
$scope.getIndiansCount = function(employees, count) {
angular.forEach(employees, function(employee) {
if(employee && employee.country === "Indian") {
count++;
}
});
return count;
};
修改
如果你不想添加循环,你的确可以使用 NG-重复
来执行递增的功能。
In case you don't want to add loops, you can indeed use the ng-repeat
to execute an increment function.
首先你需要初始化你的范围indianCounts(和voteCounts)数组:
First you need to initialize an array for indianCounts (and voteCounts) in your scope:
app.controller('Controller', function ($scope) {
$scope.indiansCount = []; // Like this
$scope.voteCount = [];
...
然后,你需要这些功能:
Then you need these functions:
$scope.initCount = function(i) {
$scope.indiansCount[i] = 0;
$scope.voteCount[i] = 0;
}
$scope.incrementCount = function(empl, i) {
if(empl.country === "Indian") {
$scope.indiansCount[i]++;
}
if(empl.employee && empl.employee.canVote === true) {
$scope.voteCount[i]++;
}
};
最后,这里是与HTML所需要的所有东西:
Finally, here is the HTML with all the stuff needed:
<div ng-app='myApp' ng-controller="Controller">
<!-- Here you keep a trace of the current $index with i -->
<div ng-init="initCount(i = $index)" ng-repeat="emp in records">
<b>Can Vote :</b> {{voteCount[i]}}<br>
<b>Indians :</b> {{indiansCount[i]}}
<div ng-repeat="empl in emp" ng-init="incrementCount(empl, i)">
{{empl.country}}<br>
{{empl.employee.name}}<br>
{{empl.employee.canVote}}
<hr>
</div>
</div>
</div>
下面是的jsfiddle 更新
这篇关于AngularJS:计数,而在嵌套NG重复迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!