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:

app.directive 'selectPlugin', [ ->
{
restrict: 'A'
link: (scope, elem, attr) ->
angular.element(elem).select2 { placeholder: attr.selectPlugin }
}
]

Here’s the gist: https://gist.github.com/ragingprodigy/e775a84c2d47220e1866

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:

.directive 'remoteSelectPlugin', ['$http', '$rootScope', ($http, $rootScope) ->
{
restrict: 'A'
link: (scope, elem, attr) ->
angular.element(elem).select2({
placeholder: attr.remoteSelectPlugin
minimumInputLength: 3
allowClear: true
query: (options) ->
$http.get "http://example.com/search?q="+ options.term.toUpperCase()
.then (response) ->
options.callback({more:false, results: response.data})
formatResult: (r) ->
'<p>' + r.title2 + '</p>' + '<span class="label label-primary">' + r.id + '</span>' + '<span class="label label-success pull-right">' + r.date + '</span>'
formatSelection: (record) ->
"#{record.title2} - #{record.suitno}"
dropdownCssClass: "bigdrop"
escapeMarkup: (m) -> m
})
}
]
Here's the gist: https://gist.github.com/ragingprodigy/671142d37a7c588383ba
Show your support

Clapping shows how much you appreciated Voice of Reason’s story.