Skip to content

Instantly share code, notes, and snippets.

@sgimeno
Last active August 29, 2015 14:00
Show Gist options
  • Save sgimeno/11402390 to your computer and use it in GitHub Desktop.
Save sgimeno/11402390 to your computer and use it in GitHub Desktop.
AngularJS filter with cached data got from a service using promise API
app.filter("testf", function($timeout) {
var data = null; // DATA RECEIVED ASYNCHRONOUSLY AND CACHED HERE
var invoked = false
function realFilter(value) { // REAL FILTER LOGIC
return ...;
}
return function(value) { // FILTER WRAPPER TO COPE WITH ASYNCHRONICITY
if( data === null ) {
if (!invoked){
invoked = true;
// IF IT HAS NOT BEEN CALLEd YET, CALL THE SERVICE THAT FETCHES THE DATA HERE
callService.then(function(result) {
data = result;
});
}
return "-"; // PLACEHOLDER WHILE LOADING, COULD BE EMPTY
}
else return realFilter(value);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment