简体   繁体   中英

Angular autocomplete with filter:search

I'm looking for a "event" between "filter:search" and my Server-request using $http.

Like "autocomplete" on every input keystroke my $http should start a new request

<input ng-model="search">
<li ng-repeat="friend in friends | filter:search">
  {{friend.name}}
</li>

Pseudocode..

// set inputdata
var sPostData = "filter:search";

$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";

$http.post(sUrl,sPostData).then(function(friendsResponse) {
 $scope.friends = friendsResponse.data.ResultSet.result;


});

Is there any hint or example to do this or wrong concept?

You can use ng-change directive ie

HTML:

<input ng-model="search" ng-change="getData()">
<li ng-repeat="friend in friends | filter:search">
      {{friend.name}}
</li>

JS:

//call server on 'search' change

$scope.getData = function(){

    $http.post(.....)

}

If you want to do make autosuggestion-like functionality with AJAX data loading, then Angular filter is not right tool for this. Instead you can make use of $scope.$watch expression:

$scope.$watch('search', function(newValue, oldValue) {
    if (newValue !== oldValue) {
        $http.post(sUrl, {filter: $scope.search}).then(function(friendsResponse) {
            $scope.friends = friendsResponse.data.ResultSet.result;
        });
    }
});

And corresponding HTML:

<input ng-model="search" ng-model-options="{ updateOn: 'default blur', debounce: {'default': 500, 'blur': 0} }">

<li ng-repeat="friend in friends">
    {{friend.name}}
</li>

Note, that you no longer need | filter:search | filter:search part. I also added ngModelOptions for better experience.

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