Angular autocomplete directive with custom field names

A short example of using jquery’s autocomplete with angularjs. Code needs some optimization.

directive_app.directive('autoComplete', function ($timeout) {
    return function (scope, element, attrs) {
        element.autocomplete({
            minLength: 1,
            source: function (request, response) {
                var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
                var mapper = $.map(scope[attrs.uiItems], function (item) {
                    return {
                        label: item.custom_field_name,
                        value: item.custom_field_name,
                        id: item.id
                    };
                });
                response($.grep(mapper, function (value) {
                    return matcher.test(value.label);
                })
                );
            },
            select: function (event, ui) {
                $timeout(function () {
                    element.trigger('input');
                }, 0);

                if (attrs.updateModelOnSelect) {
                    scope.$apply(function () {
                        scope[attrs.updateModelOnSelect] = ui.item;
                    });
                }
            }
        }).data("ui-autocomplete")._renderItem = function (ul, item) {
            return $("<li>")
                .append("<a>" + item.label + "</a>")
                .appendTo(ul);
        };
        ;
    };
});

Example usage:

<input type="text" autocomplete="off" data-auto-complete="" data-ui-items="controller_scope_var_to_get_data_from" data-update-model-on-select="controller_scope_var_to_put_selected_item" />

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>