Skip to content

Instantly share code, notes, and snippets.

@ethanph5
Last active October 26, 2016 21:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save ethanph5/6554975 to your computer and use it in GitHub Desktop.
Save ethanph5/6554975 to your computer and use it in GitHub Desktop.
AngularJS directive using bootstrap-multiselect, works on Chrome and FF.
// AngularJS: 1.3.15
// bootstrap-multiselect: 0.9.6
angular.module('yourApp')
.directive('yourDirective', function () {
return {
link: function (scope, element, attrs) {
element.multiselect({
buttonClass: 'btn',
buttonWidth: 'auto',
buttonContainer: '<div class="btn-group" />',
maxHeight: false,
buttonText: function(options, select) {
if (options.length == 0) {
return 'None selected <b class="caret"></b>';
}
else if (options.length > 3) {
return options.length + ' selected <b class="caret"></b>';
}
else {
var selected = '';
options.each(function() {
selected += $(this).text() + ', ';
});
return selected.substr(0, selected.length -2) + ' <b class="caret"></b>';
}
}
// Replicate the native functionality on the elements so
// that angular can handle the changes for us.
onChange: function(optionElement, checked) {
if (optionElement != null) {
optionElement.removeAttr('selected');
}
if (checked) {
optionElement.prop('selected', 'selected');
}
elem.change();
}
});
// Watch for any changes to the length of our select element
scope.$watch(function () {
return element[0].length;
}, function () {
$scope.$applyAsync(element.multiselect('rebuild'));
});
// Watch for any changes from outside the directive and refresh
scope.$watch(attrs.ngModel, function () {
element.multiselect('refresh');
});
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment