1

Posts have a title and an array of users who have liked the post:

{
  "title" : "Example Title",
  "likes" : ["User 1", "User 2", "User 3"]
}

I am displaying the "posts" like this:

<div ng-repeat="post in posts">
  <h1>{{post.title}}</h1>
  <span ng-show="doesLike(post.likes)">Liked already</span>
  <span ng-hide="doesLike(post.likes)">Like this post</span>
</div>

and I have a function in my controller doesLike() that returns true or false depending on whether the current user's username is in the array that is passed to the function. While this approach works can I achieve the same thing using a filter as I think this would be cleaner?

1
  • I would recommend a ng-if Commented May 23, 2016 at 11:59

2 Answers 2

1

I don't think this is gonna be cleaner to have the logic in the view.
What will be cleaner is to don't call the doesLike function twice by digest cycle by using ng-switch:

<div ng-repeat="post in posts">
    <h1>{{post.title}}</h1>
    <span ng-switch="doesLike(post.likes)">
        <span ng-switch-when="true">
            Liked already
        </span>
        <span ng-switch-default>
            Like this post
        </span>
    </span>
</div>
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks - I like this approach
1

You can try this:

<div ng-repeat="post in posts">
<h1>{{post.title}}</h1>
<span ng-if="doesLike(post.likes)">Liked already</span>
<span ng-if="!doesLike(post.likes)">Like this post</span>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.