Reputation: 7605
My Html Form looks like
<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>
My JavaScript code is
$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);
};
I know I can use ng-model-options="{ debounce: 300 }" but I'm being asked to learn $timeout and how to cancel that event while the user is still typing. GitHub has a rate limit and if the user types too fast, GitHub returns a http 403 error
Upvotes: 2
Views: 281
Reputation: 123739
Here is a way you could do with timeout.
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");
});
}
});
Upvotes: 3