ui-selct onchange loading options from the server (upgraded from select2)

134 Views Asked by At

I've recently upgraded from select2 to ui-select. I will show below how it was working using select2.

Context : I have a data of clients that needs to be filtered using ui-select.

Since the data of clients is large and could be more than 100000, I can't load it once then filter with ui-select. I need to make a query to the server onchange event (input change event with delay) and limit the results to 10.

Select2 Html :

<div
     st-input-event="change"
     st-search="_company_owner"
     style="width: 100%"
     ui-select2="ClientSelect2Options(true)"
     ng-model="company"
     name="company"
     class="text"
     class="form-control "
     placeholder="{{'SEARCH_BY_COMPANY' | translate}}"></div>
</td>

Select2 javascript :

$scope.ClientSelect2Options = function (allowClear) {
    return {
        allowClear: allowClear,
        id: function (e) { return e },
        ajax: {
            transport: function (params) {
                params.beforeSend = function (request) { request.setRequestHeader("Authorization", 'Bearer ' + $window.sessionStorage.token); };
                return $.ajax(params);
            },
            url: $rootScope.config.API_URI + '/company/query?limit=' + 10 + '&page=' + 1,
            dataType: "json",
            type: "POST",
            quietMillis: 500,
            data: function (term) {
                return { query: { name: { "$regex": term, "$options": "i" } } }; },
            results: function (data) {
                return { results: data.result }; }
        },
        initSelection: function (element, callback) {
            var id = $(element).select2('val');
            if (id && id.length > 0) {
                return companySrv.getCompanyById(id, function (res) {
                    if (res && res.success) {
                        callback(res.result);
                    } else { callback(null); }
                }, function () { callback(null); })
            }
        }
    }
};

Is it possible to query from the server using ui-select and how ?

0

There are 0 best solutions below