Skip to content

Instantly share code, notes, and snippets.

@MrAntix
Last active April 27, 2017 17:01
Show Gist options
  • Save MrAntix/0db8650f788729890f08 to your computer and use it in GitHub Desktop.
Save MrAntix/0db8650f788729890f08 to your computer and use it in GitHub Desktop.
AngularJS Multi Select (checkbox list)
// what the data looks like
// demo http://jsbin.com/yocolomife/1/edit?html,js,output
scope.things = [
{ id : 1, name: 'raindrows on roses' },
{ id : 2, name: 'wiskers on kittens' },
{ id : 3, name: 'brown paper packages tied up with strings' }
];
scope.myModel = {
favoriteThings: [1,2]
};
<div class="form-control" id="a-list-of-things">
<label ng-repeat="thing in things">
<div select-multiple="thing.id"
ng-model="myModel.favoriteThings"></div>
{{thing.name}}
</label>
</div>
'use strict';
var module = angular.module('antix.select.multiple', [
])
.directive(
'selectMultiple',
[
'$log', '$parse',
function ($log, $parse) {
return {
restrict: 'A',
scope: {},
require: 'ngModel',
template: '<span><input type="checkbox" ng-model="checked" /></span>',
replace: true,
link: function (scope, element, attrs, ngModel) {
var value = $parse(attrs.selectMultiple)(scope.$parent),
contains = function (items, item) {
if (angular.isArray(items)) {
for (var i = items.length; i--; i >= 0) {
if (angular.equals(items[i], item))
return true;
}
}
return false;
},
add = function (items, item) {
items = angular.isArray(items) ? items : [];
if (!contains(items, item))
items.push(item);
return items;
},
remove = function (items, item) {
if (angular.isArray(items)) {
for (var i = items.length; i--;) {
if (angular.equals(items[i], item)) {
items.splice(i, 1);
break;
}
}
}
return items;
};
ngModel.$render = function () {
scope.checked = contains(ngModel.$modelValue, value);
};
scope.$watch('checked', function (newValue, oldValue) {
if (newValue === oldValue) return;
var items = newValue
? add(ngModel.$modelValue, value)
: remove(ngModel.$modelValue, value);
ngModel.$setViewValue(items);
});
}
};
}
]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment