16.07.2017 Views

AngularJS Essentials

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 4<br />

var result = [];<br />

angular.forEach(cars, function (car) {<br />

if (_matches(car, criteria)) {<br />

result.push(car);<br />

}<br />

});<br />

resultCallback(result);<br />

}, 1000);<br />

};<br />

var _matches = function (car, criteria) {<br />

return angular.toJson(car).indexOf(criteria) > 0;<br />

};<br />

return {<br />

filter: _filter<br />

}<br />

});<br />

A very common requirement when creating an instant search is to cancel the<br />

previously scheduled timeout, replacing it with a new one. It avoids an unnecessary<br />

consumption of resources, optimizing the whole algorithm.<br />

In the following code, we are interrupting the timeout. It can be achieved by calling<br />

the cancel method on the $timeout object that is passing the promise reference as<br />

a parameter:<br />

parking.factory('carSearchService', function ($timeout) {<br />

var filterPromise;<br />

var _filter = function (cars, criteria, resultCallback) {<br />

$timeout.cancel(filterPromise);<br />

filterPromise = $timeout(function () {<br />

var result = [];<br />

angular.forEach(cars, function (car) {<br />

if (_matches(car, criteria)) {<br />

result.push(car);<br />

}<br />

});<br />

resultCallback(result);<br />

}, 1000);<br />

};<br />

var _matches = function (car, criteria) {<br />

[ 97 ]<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!