Using jQuery Select2 and AngularJs


This past week, I’ve been working on an AngularJS app for the entry and administration of some company data. As dictated by the application’s requirements, users need to be able to make choices from a restricted list of options and so I turned to my trusty “<select>” tag.

I soon noticed though that the options in some part of the application would grow and then make life a bit difficult for the users as they try to choose and this is where the jQuery plugin – Select2 – swooped in to save the day (or so I thought).

As it’s highly discouraged in most quarters to modify the DOM within AngularJS controllers, I needed to wrap my usage of the plugin in an AngularJS directive. Doing this was pretty easy though as I show below using a snippet of my Coffeescript code:

Here’s the gist:

I was pretty happy with this because it worked for my simple “select” controls. I was however a bit confused when trying to implement Select2’s remote data feature. Basically, I wanted users to be able to search a remote location and present the results to them using select2.

It would have been easier had I been using plain JavaScript (or so I think) but I wasn’t and I had to figure it out. I then looked at the documentation for Select2 but I hit snags.

Finally, this is the solution that worked for me:

Here’s the gist: