Reputation: 163
I have a text box
to enter some text to search records. I am using data-ng-model-options="{ debounce: 1000 }"
with keyup
event, data-ng-model-options"
working fine, but I want to fire keyup
event after the debounce
time duration.
Currently keyup
event fires instantly before debounce duration
. May be I doing something wrong.
Here is my HTML
<input type="text" id="focusOnMe" placeholder="Search..."/ data-ng-keyup="loadSearchResult($event)" data-ng-model="searchText" ng-model-options="{ debounce: 1000 }">
And this is my Keyup event
action
$scope.loadSearchResult = function(event) {
$rootScope.hideSearchResult = true;
$rootScope.showLoading = true;
var searchText = $scope.searchText.trim();
if (searchText.length > 0) {
$http({
method: 'POST',
url: '/secure/search',
data: {
searchText: searchText,
peopleFlag: checkboxValueForPeopleSearch,
colonyFlag: checkboxValueForColonySearch
}
}).success(function(data) {
console.log(data);
if (data !== undefined || data !== null) {
$timeout(function() {
$rootScope.hideSearchResult = false;
$rootScope.showLoading = false;
$scope.allSearchResult = {
"bookmarks": data.bookmarks,
"people": data.people,
"colonies": data.colonies
};
}, 300);
} else {
$rootScope.showLoading = false;
commonNotification($rootScope, false, true, true, 'something went wrong!');
$timeout(function() {
$rootScope.newStatus = false;
}, 2000);
}
}).error(function(err) {
});
} else {
$rootScope.hideSearchResult = true;
$rootScope.showLoading = false;
}
};
Sorry the code is dependent to more files, so that I don't have plunker
example
Any suggestion will be helpful for me.
Thank You
Upvotes: 4
Views: 4142
Reputation: 7282
Debounce doesn't affect the keyup event. It only delays the assigning of the model ($scope) variable. So your keyup event fires immediately and loadSearchResult runs before you want it to.
To solve it, you can add a watch tied to $scope.searchText.
$scope.$watch('searchText', function (newValue) {
loadSearchResult(newValue);
});
Super-simple and cleanly-coded because we're using the Single Source of Truth ($scope).
Note: I omitted the event object because you're not using it.
Upvotes: 4
Reputation: 3012
Once you specify debounce in ng-model-options, it will change the way model gets updated. But it won't change how key event works. For your case, use _.debounce would help:
var delay = 500;
$scope.loadSearchResult = _.debounce($scope.loadSearchResult, delay);
Upvotes: 3