问题
I'm new in AngularJS and trying to achieve check/uncheck all check boxes by clicking "toggle" button, which is styled by bootstrap.
Markup:
<button id="toggle" class="btn btn-link btn-mini" ng-click="setActionTypesAllCheck()">Check all</button>
<div class="row-fluid" ng-repeat="at in actionsQuery.actionTypes">
<div class="checkbox">
<label><input type="checkbox" ng-model="at.checked">{{at.Description}}</label>
</div>
</div>
JavaScript:
$scope.setActionTypesAllCheck = function () {
$.each($scope.actionsQuery.actionTypes, function (i, cb) {
cb.checked = !cb.checked;
});
};
At this moment the code in JavaScript checks and unchecks all check boxes, but it doesn't take into account if some of them was manually checked/unchecked, which means it doesn't work properly.
So, I need to check all check boxes by clicking "toggle" button and change its name to "Uncheck all" no matter if some of check boxes is checked or not and vice versa, that is to uncheck all check boxes and change its name to "Check all" no matter if some of check boxes is checked or not.
回答1:
var app = angular.module("app", []);
function MainCtrl() {
var vm = this;
vm.message = "Welcome";
vm.actionsQuery =
{
actionTypes: [
{
checked: true,
Description: "Jon"
}, {
checked: false,
Description: "Bon"
}, {
checked: false,
Description: "Tim"
}
]
};
vm.selected = function() {
}
vm.checkoxesState = true;
vm.UpdateCheckboxes = function() {
angular.forEach(vm.actionsQuery.actionTypes, function(at) {
at.checked = vm.checkoxesState;
});
vm.checkoxesState = !this.checkoxesState
};
}
angular.module("app").controller("MainCtrl", MainCtrl);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html ng-app="app">
<body ng-controller="MainCtrl as vm">
<div class="container">
<h3>{{vm.message}}</h3>
<form>
<button id="toggle" class="btn btn-link btn-mini" ng-click="vm.UpdateCheckboxes()">
<span ng-show="vm.checkoxesState"> Check all </span>
<span ng-hide="vm.checkoxesState"> Uncheck All </span>
</button>
<div class="row-fluid" ng-repeat="at in vm.actionsQuery.actionTypes">
<div class="checkbox">
<label>
<input type="checkbox" ng-model="at.checked">{{at.Description}}</label>
</div>
</div>
</form>
</div>
</body>
</html>
回答2:
I have been using this directive for checkboxes. Its simple and it has examples that you need.
来源:https://stackoverflow.com/questions/26017286/how-to-check-uncheck-all-check-boxes-using-angularjs