md-items is not updating the suggesion list proper

2019-02-18 17:50发布

问题:

I'm using md-autocomplete, in that md-items which is not updating the response list properly which is obtained from the Service Host - Ajax Call.

HTML Source Code

<md-autocomplete flex required
    md-input-name="autocompleteField"
    md-no-cache="true"
    md-input-minlength="3"
    md-input-maxlength="18"
    md-selected-item="SelectedItem"
    md-search-text="searchText"
    md-items="item in querySearch(searchText)"
    md-item-text="item.DisplayName" Placeholder="Enter ID" style="height:38px !important;">
    <md-item-template>
        <span class="item-title">
            <span md-highlight-text="searchText" md-highlight-flags="^i"> {{item.ID}} </span>
            <span> - </span>
            <span md-highlight-text="searchText"  md-highlight-flags="^i"> {{item.Description}} </span>
        </span>
    </md-item-template>
</md-autocomplete>

AngularJS Script

//bind the autocomplete list when text change
function querySearch(query) {
    var results = [];
    $scope.searchText = $scope.searchText.trim();
    if (query.length >=3) {
        results = LoadAutocomplete(query);
    }
    return results;
}

//load the list from the service call
function LoadCPTAutocomplete(id) {
    TestCalculatorService.searchAutocomplete(id).then(function (result) {
        if (result.data != null) {
            $scope.iList = result.data;
        } else {
            $scope.iList = [];
        }
    });
    return $scope.iList;
}

I'm getting the autocomplete list from the Service Host. I'm getting the response properly, but it does not update in the UI properly.

Screen Shot 1:

Here I'm searching for 8224 but it shows the result for 822. I debugged the issue in Firebug, see the above Screen shot it shows, the request was sent for the search term 8224 and I got the response of two matching items as a JSON Object, which is shown in the below Screen Shot 2

In UI, it shows the result 82232, 82247, 82248, 82270. But actually Service return is 82247 and 82248.

How to update the Item-source in UI for Angular Material md-autocomplete? Kindly assist me.

Supportive Question was posted in the following link Manually call $scope.$apply raise error on ajax call - Error: [$rootScope:inprog]

回答1:

The Answer Marked in the following post is Correct as per the requirement. $http issue - Values can't be returned before a promise is resolved in md-autocomplete Angular Material

  • .then() - full power of the promise API but slightly more verbose
  • .success() - doesn't return a promise but offers slightly more convenient syntax

Don't use .success(), use .then to get the updated result in the UI...