Let's say I have an input text field (more like the Google search field) which, when changed, will trigger a request and show some results.
For instance,
Let's type in Dog in 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 the DOG one. My model would end up with the DO results, even if I typed DOG.
For that, I need a way to cancel or abort current ongoing requests if I keep on typing characters. That way, my model is only changed by the final request.
My input looks like the following:
<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;
    });
}
                Usually for this case people use ng-model-options={debounce: 100}.
https://docs.angularjs.org/api/ng/directive/ngModelOptions
anyway you can reject promise.
I think you want to use a debounce technique in this case?
see:
http://ilikekillnerds.com/2014/12/increasing-angular-performance-by-debouncing-your-ng-model-updates/
<input type="text"
   class="form-control" 
   data-ng-model="query" 
   data-ng-change="ctrl.search(query)" 
   placeholder="Search" 
   ng-model-options="{ debounce: { 'default': 500,  'blur': 0 } }"    
/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With