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

Benjamin Roth
InstructorBenjamin Roth
Share this video with your friends

Social Share Links

Send Tweet
Published 9 years ago
Updated 5 years ago

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

[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.

egghead
egghead
~ an hour ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today