繁体   English   中英

Angular.JS如何为即时搜索添加延迟?

[英]Angular.JS how to add a delay to Instant Search?

我的HTML表单看起来像

    <form class="navbar-form navbar-left" role="search" name="userName">
      <div class="form-group">
        <input type="text" class="form-control" placeholder="Search Git By Username" ng-model="user" ng-change="searchForUser()" autofocus>
      </div>
    </form>

我的JavaScript代码是

 $scope.searchForUser = function() {
        $scope.selectedUser = null;
        $scope.selectedRepo = null;
        $scope.returnedRepos = [];
        $scope.returnedCommits = [];
        var url = "https://api.github.com/search/users?q=" + $scope.user;
        if($scope.user.length === 0){
            $scope.returnedUsers = null;
            return;
        }

        function updateUsers() {

            $http.get(url).
                success(function(data,status) {
                    if(status===200) {
                        $scope.returnedUsers = data.items;
                    }
                }).
                error(function(data,status){
                    alert("something happened with quhhnnhhhh");
                });
        }

        if($scope.userSearchTextTimeout)
        {
            $timeout.cancel($scope.userSearchTextTimeout);
        }
        $scope.userSearchTextTimeout = $timeout(function()
        {
            $scope.user = $scope.user;
        }, 500);
 };

我知道我可以使用ng-model-options =“ {debounce:300}”,但是系统要求我学习$ timeout以及如何在用户仍在键入时取消该事件。 GitHub有速率限制,如果用户输入速度太快,则GitHub返回http 403错误

这是超时的一种方法。

app.controller('MainCtrl', function ($scope, $timeout, $http) {
    //keep a variable for storing timeoutPromise
    var timeoutPromise;

    $scope.searchForUser = function () {
        $scope.selectedUser = null;
        $scope.selectedRepo = null;
        $scope.returnedRepos = [];
        $scope.returnedCommits = [];

        if ($scope.user.length === 0) {
            $scope.returnedUsers = null;
            return;
        }

        //if already a timeout is in progress cancel it
        if (timeoutPromise) {
            $timeout.cancel(timeoutPromise);
        }

        //Make a fresh timeout
        timeoutPromise = $timeout(searchUsers, 500)
                         .finally(function(){
                             timeoutPromise = null; //nullify it
                          });

    };

    function searchUsers() {
        $http.get("https://api.github.com/search/users?q=" + $scope.user).
        success(function (data, status) {
            if (status === 200) {
                $scope.returnedUsers = data.items;
            }
        }).
        error(function (data, status) {
            alert("something happened with quhhnnhhhh");
        });

    }
});

Plnkr

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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