I have a table of objects with checkbox inputs. If an object's checkbox is checked, the object.isChecked value is set to true, and if it's unchecked then the value is set to false. However, I have a master checkbox that checks/unchecks all the checkboxes in the table. This does not update the object.isChecked values however. How would I make the master checkbox change the object.isChecked values?
-
Can you create a plunker with the example? It's easier to find out =)Deividi Cavarzan– Deividi Cavarzan2013-08-13 22:52:17 +00:00Commented Aug 13, 2013 at 22:52
-
1possible duplicate of How can I get angular.js checkboxes with select/unselect all functionality and indeterminate values?zs2020– zs20202013-08-13 23:08:54 +00:00Commented Aug 13, 2013 at 23:08
Add a comment
|
1 Answer
The problem must be you trigger checkboxes not inside Angular. If you want Angular magic to work - you must do all your model manipulations inside Angular scope. I've created a plunker to demonstrate.:
index.html
<!DOCTYPE html>
<html data-ng-app="demo">
<head>
<script data-require="[email protected]" data-semver="1.9.0" src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.9.0/jquery.js"></script>
<script data-require="angular.js@*" data-semver="1.0.7" src="http://code.angularjs.org/1.0.7/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body data-ng-controller="DemoController">
<div data-ng-repeat="object in objects">
{{object.name}}: <input type="checkbox" data-ng-model="object.isChecked">
</div>
Master: <input type="checkbox" data-ng-click="triggerAll()">
{{objects}}
</body>
</html>
script.js
"use strict";
var demo = angular.module("demo", []);
function DemoController($scope) {
$scope.objects = [
{
name : "First",
isChecked : true
},
{
name : "Second",
isChecked : false
}
]
$scope.triggerAll = function(){
angular.forEach($scope.objects, function(value){
value.isChecked = !value.isChecked;
})
}
}
Pay attention that triggering all checkboxes is done with ngClick, not with usual onClick or jQuery handler. This allows Angular to run dirty checks and behave correctly.
2 Comments
Corbin Lewis
I was already writing a solution similar to this, but I had hoped there was a built in angular way of doing it. Thank you.
madhead
I do not think it is possible to bind several bools to one checkbox.