mikeerickson
12/1/2015 - 5:27 AM

AngularJS directive using bootstrap-multiselect, works on Chrome and FF.

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');
                });
 
            }
 
        };
    });