Last active
February 15, 2017 10:34
-
-
Save ghengeveld/8669299 to your computer and use it in GitHub Desktop.
AngularJS Select All directive
This file contains 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
/** | |
* 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); | |
}); | |
} | |
}; | |
}) |
Awesome work!
Unfortunately there's an issue when using checkboxes that are wrapped in another directive.
The indeterminate feature is not working, and toggling the checkboxes doesn't update the select-all checkbox state.
See a demo here: https://plnkr.co/edit/AekVeiDndoOLE1LLCXoz?p=preview
Setting the $timeout to 300 or more seems to take care of the problem, but changing priority for the directives doesn't.
Any fix?
is there something for angular2?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
But its not working with Pagination ? And its not calling the ng-change='myFunction()' ? but should cause the Value is changing ?
Not compatible with AngularMaterial or Bootstrap.
But still great beginngin need only a lil bit update it seems