Created
August 1, 2013 08:13
-
-
Save arnabdas/6129431 to your computer and use it in GitHub Desktop.
Tri-State Checkbox in AngularJS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- http://plnkr.co/edit/N98IKTcHoZMCs18FjSRF?p=preview --> | |
The directive assumes that the checkboxes array contains objects that have an isSelected property and a desc property. | |
<tri-state-checkbox checkboxes="listelements"></tri-state-checkbox> | |
or | |
<!-- http://plnkr.co/edit/PTnzedhD6resVkApBE9K?p=preview --> | |
If you prefer to have the directive only render the tri-stated checkbox, hence the individual checkboxes are in the HTML: | |
<tri-state-checkbox checkboxes="listelements" class="select-all-cb"> | |
</tri-state-checkbox>select all | |
<div ng-repeat="item in listelements"> | |
<input type="checkbox" ng-model="item.isSelected"> {{item.desc}} | |
</div> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
app.directive('triStateCheckbox', function() { | |
return { | |
replace: true, | |
restrict: 'E', | |
scope: { checkboxes: '=' }, | |
template: '<div><input type="checkbox" ng-model="master" ng-change="masterChange()">' | |
+ '<div ng-repeat="cb in checkboxes">' | |
+ '<input type="checkbox" ng-model="cb.isSelected" ng-change="cbChange()">{{cb.desc}}' | |
+ '</div>' | |
+ '</div>', | |
controller: function($scope, $element) { | |
$scope.masterChange = function() { | |
if($scope.master) { | |
angular.forEach($scope.checkboxes, function(cb, index){ | |
cb.isSelected = true; | |
}); | |
} else { | |
angular.forEach($scope.checkboxes, function(cb, index){ | |
cb.isSelected = false; | |
}); | |
} | |
}; | |
var masterCb = $element.children()[0]; | |
$scope.cbChange = function() { | |
var allSet = true, allClear = true; | |
angular.forEach($scope.checkboxes, function(cb, index){ | |
if(cb.isSelected) { | |
allClear = false; | |
} else { | |
allSet = false; | |
} | |
}); | |
if(allSet) { | |
$scope.master = true; | |
masterCb.indeterminate = false; | |
} | |
else if(allClear) { | |
$scope.master = false; | |
masterCb.indeterminate = false; | |
} | |
else { | |
$scope.master = false; | |
masterCb.indeterminate = true; | |
} | |
}; | |
$scope.cbChange(); // initialize | |
}, | |
}; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment