gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 19:26:04 25 4
gpt4 key购买 nike

我的 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

关于javascript - Angular.JS 如何为即时搜索添加延迟?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30745351/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com