Enter Your Email Address to Watch This Lesson

Your link to unlock this lesson will be sent to this email address.

Unlock this lesson and all 1055 of the free egghead.io lessons, plus get Angular 1.x content delivered directly to your inbox!



Existing egghead members will not see this. Sign in.

Stateful filters with promises in AngularJS

4:44 Angular 1.x lesson by

This lesson illustrates how to use promises inside Angular filters

Get the Code Now
click to level up

egghead.io comment guidelines

Avatar
egghead.io

This lesson illustrates how to use promises inside Angular filters

Here, we have a list of artists with their associated category IDs, and here, we have the list of the categories. Our end result would be to list of artists with that category name.

Our setup is the following. We have a data service which returns two promises. Promises are responsible to fake Ajax requests, and return the artist array and the music categories there.

We have a controller, which fetches data, and we have our filter, which is supposed to return a category name from a music category ID. Let's try to implement our filter. It would consist in using our data service. Once we have our music categories, we can try to get the category.

Let's check my ID. I have Lodash set up, so I can do it pretty easily. If I have a category, I can return category name. But actually, that doesn't work. It isn't updated, and it keeps the initial data by return.

Let's take a look at the angle argumentation, particularly, the stateful filter section, where you can see stateful filters are strongly discouraged.

You can see they are executed one or more times during each digest cycle. We could make our filter stateful right now, but this would break badly, I already tried. Let's start with implementing the cache implementation. Our cache would be a mere JavaScript object, and there, if our cash contains the expected music category ID, I could return it right away.

Otherwise, I could send it right away with some waiting text like fetching. There, instead of returning, I would set my cache with the category name. Our output here is empty, we have to make our filter stateful in order to have the expected behavior. You can see it was fetching, and then, we have our titles.

Let's see it again in action. It's fetching, and what's the categories are found, are retrieved from the server, they are properly displayed. What I strongly encourage is to cache the promises, because they are going to be queried a lot within the filter, let's do that.

We add a cache again, in our data service. Here, if cache notes music categories exist, we are going to return it right away. Or else, we are going to store our promise inside, and we return our promise here. As you can see, the behavior has not changed, but we have some more optimization.


Featured course:

Building apps with Ionic 2

Building apps with Ionic 2

HEY, QUICK QUESTION!
Joel's Head
Why are we asking?