我的AngularJS控制器正在調用API來獲取成員列表。可以使用多個過濾器來查詢API,例如年齡範圍,姓名搜索,郵政編碼等。檢查任何正在進行的背景API調用,以在AngularJS中完成
我想要完成的是讓用戶感覺搜索速度非常快。所以當用戶過濾時,我正在監視過濾器的變化。當過濾器發生變化時,我立即執行新的搜索API調用,而不是等待用戶單擊「搜索」。
這個想法是,當用戶完成過濾並點擊「搜索」時,系統應該已經完成搜索並可以輸出搜索結果。
問題:當用戶點擊「搜索」和publish()
函數被調用,我必須確保沒有API搜索是目前正在進行中,如果一個是,等待它完成。然後,我將隱藏的memberslist.temp
的搜索結果發佈到可見memberslist.members
。
// Current code works, except the publish function. See the TODO:
app.controller('SearchCtrl', ['$scope', 'Restangular', '$timeout', function($scope, Restangular, $timeout) {
// Pushes prefetched search results over to the visible search results
// TODO: Check if search is ongoing...
$scope.publish = function() {
$scope.memberslist.members = $scope.memberslist.temp;
};
// Watch filters for changes
var searchTimer = false;
var previousSearch = [$scope.name, $scope.minAge, $scope.maxAge];
$scope.$watch('[name, minAge, maxAge]', function(newVal, oldVal, scope){
if (searchTimer) {
$timeout.cancel(searchTimer);
}
// Do search only after the user has stopped typing for 400 ms
searchTimer = $timeout(function(){
if (!_.isEqual(newVal, previousSearch)) {
previousSearch = newVal;
scope.search();
}
}, 400);
}, true);
$scope.search = function() {
var query_params = {
name: $scope.name,
price_min: $scope.minAge,
price_max: $scope.maxAge
};
Restangular.all('members').getList(query_params)
.then(function(members){
$scope.memberslist.temp = members;
});
};
}]);
我首先想到的是設置像isSearching = true的變量,然後設置爲false一旦搜索調用返回它的結果。似乎無法讓它工作。
你爲什麼不看看angularui typeahead http://angular-ui.github.io/bootstrap/ – Chandermani
感謝您的指點:) Typeahead將使用對數據存儲的調用的承諾顯示匹配列表,如一個觸發器來更新列表。我的問題有點類似,但並不完全:想象一下,如果typeahead有一個按鈕,顯示「加載搜索結果」,然後必須檢查是否存在正在進行的搜索。 –