简体   繁体   中英

Angular-UI Select2 directive Search functionality not working

I'm using the angular-ui select2 directive. I know it's now deprecated but my application is using this directive throughout and there is an improvement I want to make.Soon, we will migrate to the new ui=select alternative.

I'm loading the json data via an ajax call as per the example here http://select2.github.io/select2/ . The data is loading correctly and can be selected, however I cannot search and narrow down/filter the results. From what i understand this is supported in the directive. when i type something, the data refreshes but doesn't filter according to the search terms. below is my code

<input type="text" id="users" ui-select2="filters.select2Test" ng-model="filters.model.users"
data-placeholder="Pick a user" ng-required="true" style="width: 300px" />

$scope.filters = {
                     select2Test: {
                    id: function(user) {
                        return user.code;
                    },
                    minimumInputLength: 3,
                    multiple: true,
                    ajax: {
                        url: 'api/employee', //This URL points to an internal location and wouldn't work 
                        dataType: 'json',

                        data: function (params) {
                            return {
                                q: params.term, // search term
                                page: params.page
                            };
                        },
                        results: function(data, page) {
                            return { results: data };
                        }
                    },

                    formatResult: function(data) {
                        return "<div class='select2-user-result'>" + data.name + "</div>";
                    },
                    formatSelection: function(data) {
                        return data.name;
                    },
                    initSelection: function(element, callback) {
                        var data = [];
                        $(element.val().split(",")).each(function(i) {
                            var item = this.split(':');
                            data.push({
                                id: item[0],
                                title: item[1]
                            });
                        });
                        callback(data);
                    }
                }
           }

A matcher needs to be added in your select2 options:

select2Test: {
    ...
    matcher: function(term, text, option) {
      return option.name.includes(term);
    },
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM