0

Trying to implement a search field with angular js.

Everytime the input value changes, it will call a method to fetch the query results.

However its very slow because for every char, it will call the method once. My input search box as below

<input type="text" name="term" ng-model="term" ng-change="run_filter()"/>

My function

$scope.do_filter = function() {
    $scope.items = [];
    var canceler;
    term = $scope.term;
    if (canceler) canceler.resolve();
    canceler = $q.defer();
    $http({
        method: 'GET',
        url: '/search/do_search',
        params: {
            term: term
        },
        timeout: canceler.promise
    }).success(function(result) {
        if (result.items != null) {
            $scope.items = result.items;
            $scope.success = true;
        } else {
            $scope.success = false;
        }
        $scope.loading = false;
    });
}

But it doesnt seem to work. When I look at the network, the first request is not cancelled when the second request is submitted.

Thanks in advance for the help.

1 Answer 1

1

Have a look at this awesome directive by @Doug R which adds a delay to ng-change.

This totally saved my day because we have some very fast typers at my office. This will only fire after a certain amount of typing inactivity (300 - 500ms are a good value to start with)

Delayed ng-change

Another way would be to react with ng-blur or force the user to press RETURN to update the list.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.