Skip to content

Instantly share code, notes, and snippets.

@ghengeveld
Last active February 15, 2017 10:34
Show Gist options
  • Save ghengeveld/8669299 to your computer and use it in GitHub Desktop.
Save ghengeveld/8669299 to your computer and use it in GitHub Desktop.
AngularJS Select All directive
/**
* Directive to instantly enable/disable multiple checkboxes based on a master checkbox.
* Changing slave checkboxes will update the master checkbox accordingly, including the indeterminate state.
*
* Usage example:
*
* <label><input type="checkbox" select-all="theProperties"> Select all</label>
* <div ng-repeat="property in properties">
* <label><input type="checkbox" rel="theProperties" ng-model="property.checked"> {{ property.label }}</label>
* </div>
*
* Note that the 'rel' attribute on slave checkboxes should match the 'select-all' attribute.
*/
.directive('selectAll', function($timeout, $parse) {
return {
restrict: 'A',
link: function (scope, masterElement, attrs) {
var slaveName = attrs.selectAll;
var slaveSelector = ':checkbox[rel="' + slaveName + '"]';
masterElement.on('click', function() {
angular.element(slaveSelector).each(function(i, elem) {
var localScope = angular.element(elem).scope();
var model = $parse(angular.element(elem).attr('ng-model'));
model.assign(localScope, masterElement.prop('checked'));
localScope.$apply();
});
});
$timeout(function() {
var slaveElements = angular.element(slaveSelector);
var setMasterState = function() {
var checkedSlaves = slaveElements.filter(function(i, elem) {
return angular.element(elem).prop('checked');
});
var isChecked = (checkedSlaves.length === slaveElements.length);
var isIndeterminate = (checkedSlaves.length > 0 && checkedSlaves.length < slaveElements.length);
masterElement.prop('checked', isChecked);
masterElement.prop('indeterminate', isIndeterminate);
};
setMasterState();
slaveElements.on('click', setMasterState);
});
}
};
})
@1010451
Copy link

1010451 commented Feb 15, 2017

is there something for angular2?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment