我创建了一个angularjs应用程序,用于打印印度人数以及那些具有投票资格的人数值的人,
该应用程序工作正常,但我不知道如何在迭代时获取印第安人和投票合格的计数
<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>
有人可以告诉我一些建议吗
您emp.country
是undefined
,因为emp
是员工的集合。您可以改为:
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-repeat
来执行增量功能。
首先,您需要在您的范围内为indianCounts(和voteCounts)初始化一个数组:
app.controller('Controller', function ($scope) {
$scope.indiansCount = []; // Like this
$scope.voteCount = [];
...
然后,您需要这些功能:
$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:
<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更新
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句