Bootstrap Angular Multiselect dropdown- jQuery in Angular


There are a number of jQuery plugins out there and truly speaking a lot of them are almost like a necessity in web applications be it a enterprise application or simple consumer blogging website.
I have worked with Angular for some time now and I always had this problem of using jQuery plugins in Angular scope. But due to the scope differences it is a bit tricky to combine these two worlds.
Recently I have been working on a project where I needed to use a select as multiselect dropdown. I have searched for options on angular modules/directives which could provide such functionality.
Fortunately I found one such solution but as a jQuery plugin.I’m really thankful to davidtutz who has worked hard to bring this plugin to life. It’s called bootstrap-multiselect which can be found at http://davidstutz.github.io/bootstrap-multiselect/.
Well enough of talk lets see how to combine this with Angular. The answer is a simple  directive.
angular.module('multi-select', []);
.directive('multiSelect',function($parse){
return function(scope, element, attributes){
var getter = $parse(attibutes.multiSelect);
var multiSelectOptions = getter(scope);
element.multiselect(multiSelectOptions);     
// Watch for any changes to the length of our select element
       scope.$watch(function () {
           return element[0].length;
       }, function () {
           element.multiselect('rebuild');
       });
       
//Watch for any changes to model
scope.$watch(attributes['ngModel'], function(){
element.multiselect('refresh');
});
}
})

A bit about the code. Firstly we are parsing the expression attached to multiselect attribute on SELECT element into “getter” variable which will fetch the corresponding object from scope context as multiSelectOptions.
Then just initialize the multiselect jQuery plugin with the options object as argument. This will just initialize the plugin once but if there are any changes to the length of select or the bound model the plugin has to be reinitialized.
So to tackle this we just need to add a watcher to our model, that’s what is happening in scope.$watch.

you can now include this module as a dependancy in your applications and use it along with bootstrap-multiselect.This will also work with late bound models.

Usage example:

<select id="example-getting-started"
multiple="multiple"
multi-select="multiselectOptions"
ng-model="selectedItem">
   <option value="cheese">Cheese</option>
   <option value="tomatoes">Tomatoes</option>
   <option value="mozarella">Mozzarella</option>
   <option value="mushrooms">Mushrooms</option>
   <option value="pepperoni">Pepperoni</option>
   <option value="onions">Onions</option>
</select>

That’s all and you are good to go.