Join egghead, unlock knowledge.

Want more egghead? It's 45% off for a limited time only!

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock All Content for 45% Off

Already subscribed? Sign In

Save 45% for a limited time.

Get access to all courses and lessons on egghead today.

Autoplay

    Extract predicate methods into filters for ng-if and ng-show

    Benjamin RothBenjamin Roth

    Leaking logic in controllers is not an option, filters are a way to refactor your code and are compatible with ng-if and ng-show

    angularjsAngularJS
    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    00:01 Say we have an app where content must be displayed based on user rights. Rights are an array within user and if it can contain admin or BMT. We have two divs, the admin div must be shown whenever the user is admin and the standard user div must be shown whenever the user isn't admin.

    00:25 We already have our logic in our controller, so now we need to add it within our template and isn't admin rule for system non user divs. This does the trick, but we have a problem in this implementation which is our business logic is leaking within our controller and it's not reusable.

    01:02 In order to solve this problem, I suggest we use a filter. This filter would be named "User" and it would return a function. Let's discuss all the details of this implementation. The filter would receive the user J subject and it would receive a rule. How would we use it? We would use it like that, main.currentuser, pipe to user filter and then the rule name.

    01:45 Say we want to have is admin and we want to have isn't admin. Currently, our filter isn't implemented, so we have to create the appropriate rules. Let's create a J subject with is admin, which would be a function which takes a user. We already have the implementation here and the isn't admin which returns the opposite of our is admin function.

    02:44 Then here, we have to return rules, rule name, and we pass the user. Here we go, we have a setup where we have our cool reusable and we can get rid of this code within our controller.

    Discuss

    Discuss