我需要计算列表中选择的项目数。
我有以下清单:
<ul>
<li ng-repeat="items in item">
<input type="checkbox" name="item_id[]" />
</li>
</ul>
有类似的东西var count = $scope.item.selected.count
吗?
更新
感谢@Stewie,我可以使用它。
我最终使用了以下代码:
// Count the number of selected items
$scope.selectedCounter = 0;
$scope.change = function (item) {
if (item.selected) {
$scope.selectedCounter++
} else {
$scope.selectedCounter--
}
};
// HTML
<ul>
<li ng-repeat="item in items">
<input type="checkbox" ng-model="item.selected" ng-change="change(item)" />
</li>
...
</ul>
<span>Count: </span> ({{selectedCounter}})
如果您还有一个select all
复选框
<input type="checkbox" ng-model="selected" class="checkAll" ng-change="selectAll(selected)" />
然后代码将是:
$scope.selectAll = function (selected) {
var items = $scope.items;
angular.forEach(items, function (item) {
item.selected = selected;
});
// Update the counter
if(selected){
$scope.selectedCounter = items.length;
} else {
$scope.selectedCounter = 0;
}
};
您对ngRepeat的使用看起来不对。它应该是“项目中的项目”,而不是相反。另外,您没有在输入中使用ng-model,这使得获取计数变得更加困难。
因此,如果添加ng-model,则可以通过许多不同的方式获得计数,其中一种是:
app.controller('AppController',
[
'$scope',
function($scope) {
$scope.items = [
{id: 1, title: "Can't Hold Us"},
{id: 2, title: "Just Give Me A Reason"},
{id: 3, title: "Mirrors"},
{id: 4, title: "Get Lucky"},
];
$scope.selectedItems = 0;
$scope.$watch('items', function(items){
var selectedItems = 0;
angular.forEach(items, function(item){
selectedItems += item.selected ? 1 : 0;
})
$scope.selectedItems = selectedItems;
}, true);
}
]
);
<body ng-controller="AppController">
<ul>
<li ng-repeat="item in items">
<label>
<input type="checkbox" name="payment_id[]" ng-model="item.selected" /> {{item.title}}
</label>
</li>
</ul>
<div>Selected Items Length: {{selectedItems}}</div>
</body>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句