Custom dropdown/auto-complete with AngularJS (Version 2)

It’s been over a year now since I released the version 1 of what I called the Custom Select directive (since it was based on the functionality of the AngularJS select directive).

Unfortunately, the designers of AngularJS decided to change the way the select directive works on version 1.4, thus breaking some of the features of this directive. So I decided to redesign it and use a different (and actually simpler) approach. So what used to be:


<div custom-select ng-model="fruit" ng-options="f for f in fruits">
</div>

is now:


<div custom-select="f for f in fruits | filter: $searchTerm" ng-model="fruit">
</div>

where $searchTerm is a parameter provided by the directive, that corresponds to the text in the search box.

Now the directive delegates the job of filtering to the programmer, letting you use any of the built-in AngularJS filters, or plugging in your own:





<div custom-select="p as p.name for p in findPeople($searchTerm)" ng-model="person">
</div>




And filter synchronously:

$scope.findPeople = function (term) {
    // Suppose we have a people array
    var found = [];
    for (var i = 0; i < people.length; i++) {
        if (/* search all properties you like */) {
            found.push(people[i]);
        }
    }
    return found;
};

Or asynchronously:

$scope.findPeople = function (term) {
    var url = 'http://mysite.com/search?q=' + encodeURIComponent(term);
    return $http.get(url); // This server call must return an array of objects
};

You can check out the new code from the GitHub repository. If you still want to use the previous version, you can find it here.

Happy coding!