如何使用angularjs计算选择/未选中复选框项目的数量?
<label class="col-xs-5 pull-left" style="font-weight: bold; margin-left: 4px; margin-top: -17px;" >You have choose <font size="3" color="green">{{checkedResult}}</font> Customer(s)</label>
<tr ng-repeat="item in $data " >
<td width="30" style="text-align: left" header="\'smsChkbx\'">
<label>
<input type="checkbox" class="ace" name="someList[]" value="{{item.somename}}" ng-model="checkboxes.items[item.somename]" />
$scope.$watch('checkboxes.items', function(values) {
if (!$scope.mydata) {
return;
}
var checked = 0,
unchecked = 0,
total = $scope.mydata.length;
angular.forEach($scope.mydata, function(item) {
checked += ($scope.checkboxesSms.items[item.somename]) || 0;
unchecked += (!$scope.checkboxesSms.items[item.somename]) || 0;
});
if ((unchecked == 0) || (checked == 0)) {
$scope.checkboxes.checked = (checked == total);
}
**if(checked != 0 && unchecked != 0){
$scope.checkedResult++;
}**
$scope.tableParamsSms.reload();
console.log($scope.checkedResult);
console.log((checked != 0 && unchecked != 0));
angular.element(document.getElementById("select_Sms")).prop("indeterminate", (checked != 0 && unchecked != 0));
}, true);
当我第一次检查时,计数正确,问题是当我取消选中已选中的那个时它也会计算
也希望在通过多重检查选项
进行检查时进行计数答案 0 :(得分:1)
您应该在复选框中进行ng-click并触发事件。
e.g:
ng-click="selectOrDeselect(item)"
然后在该函数中执行类似的操作,从列表中添加或删除它。
$scope.selectOrDeselect = function(item) {
var index = $scope.selectedItems.indexOf(item);
if (index === -1) {
$scope.selectedItems.push(item);
} else {
$scope.selectedItems.splice(index, 1);
}
};
然后有一个var count = $scope.selectedItems.length
答案 1 :(得分:0)
我无法修改您的代码,但您可以使用以下内容:
<强> HTML 强>
<div ng-app>
<h2>Sample</h2>
<div ng-controller="MyCtrl">
<div ng-repeat="item in Items">
{{item.name}} <input type="checkbox" ng-model="item.selected" ng-change="Checked(item)" />
</div>
</div>
</div>
<强> AngularJS 强>
function MyCtrl($scope) {
$scope.SelectedItems = [];
$scope.Items = [
{
id: 1,
name: "ABC",
selected: false
},
{
id: 2,
name: "DEF",
selected: false
},
{
id: 3,
name: "GHI",
selected: false
}
]
$scope.Checked = function(item) {
if (item.selected) {
$scope.SelectedItems.push(item);
}
else {
var index = $scope.SelectedItems.indexOf(item);
if (index > -1) {
$scope.SelectedItems.splice(index, 1);
}
}
console.log($scope.SelectedItems) //array of selected items
}
}