Let's say I have an input text box (more like a Google search box) that, when changed, calls up a query and shows some results.
For example,
Enter the type Dog at the input:
typed D -> Calls ctrl.search('D') -> Makes a request -> Changes model when success typed DO -> Calls ctrl.search('DO') -> Makes a request -> Changes model when success typed DOG -> Calls ctrl.search('DOG') -> Makes a request -> Changes model when success.
Now let's say that the DO request responds later than Dog . My model would end up with DO results, even if I typed Dog .
To do this, I need to cancel or interrupt current current requests if I continue to type characters. Thus, my model is changed only upon final request.
My input is as follows:
<input type="text" class="form-control" data-ng-model="query" data-ng-change="ctrl.search(query)" placeholder="Search" />
Here is my searchCtrl.js :
var search; var language; var _this; var SearchCtrl = function (searchService, lang) { search = searchService; langauge = lang; _this = this; } SearchCtrl.prototype.search = function (text) { var promise = search.language(language) .facet('characters') .highlight('quotes') .query(text); promise.then(function (response) { if(!response) return; _this.total = response.total; _this.count = response.found; _this.result = response.data; }); }
javascript angularjs promise deferred
Matias cicero
source share