Skip to content

Instantly share code, notes, and snippets.

@jwgmeligmeyling
Created May 29, 2016 22:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jwgmeligmeyling/31a03cf72f33d24409e8abadded7004a to your computer and use it in GitHub Desktop.
Save jwgmeligmeyling/31a03cf72f33d24409e8abadded7004a to your computer and use it in GitHub Desktop.
Angular bind checkbox model to array

Angular bind checkbox model to array

Angular model formatter and parser pair that transforms a set of checkboxes to an array filled with arbitrary values.

Usage

<input type="checkbox" ng-model="ctrl.myModel" data-multi-select-value="::arrayValue">
/**
* @ngdoc directive
* @restrict E
* @name nl.meylingmedia.multiselect:multiSelectValue
* @module nl.meylingmedia.multiselect
* @description
* Angular model formatter and parser pair that transforms a set of checkboxes to
* an array filled with arbitrary values.
*
* @usage
* <input type="checkbox" ng-model="ctrl.myModel" data-multi-select-value="::arrayValue">
*/
angular.module('nl.meylingmedia.multiselect').directive('multiSelectValue', function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attr, ngModel) {
ngModel.$formatters.push(function(value) {
var actualValue = scope.$eval(attr.multiSelectValue);
return angular.isArray(value) && value.indexOf(actualValue) !== -1;
});
ngModel.$parsers.push(function(value) {
var actualValue = scope.$eval(attr.multiSelectValue);
if (!angular.isArray(ngModel.$modelValue)) {
ngModel.$modelValue = [];
}
var index = ngModel.$modelValue.indexOf(actualValue);
if (value === true && index === -1 ) {
ngModel.$modelValue.push(actualValue);
}
else if (value === false || index !== -1) {
ngModel.$modelValue.splice(index, 1);
}
return ngModel.$modelValue.slice();
});
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment