How To Use JQuery Chosen In Angular JS
Posted by blogmeister on
February 24, 2015
If you have no idea what JQuery Chosen is, it is simply a plugin that makes long, unwieldy select boxes much more user friendly.
Using it with Angular JS is no problem. However, a cleaner and simpler way to use it is to make it as a Directive.
For me, this is how I did it.
|
1 2 3 4 5 6 7 8 9 10 11 |
AppIndex.directive('chosen', function () { return { restrict: 'A', link: function(scope, elem, attrs, controller) { scope.$watch(attrs.ngModel, function(n) { if (attrs.ngModel && attrs.ngModel.value) $(elem).chosen(); }); } }; }); |
I used the ngModel attribute to have the scope listen to any changes to it like setting a default value or when a user selects an item in the dropdown.
I tried to use ngOptions as my first choice and had the scope listen to ngOptions.length or attrs[‘options’].length. However when it gets loaded, since I am getting my list asynchronously from the server, it will throw out an Exception.
Not a program stopper but as a developer, nobody wants to see any kind of error messages in the console no matter how harmless they can be. In my case, since I always set all my ngModels a default value, I decided to listen to this attribute instead.









