tommyd456
tommyd456

Reputation: 10693

Angularjs filter to check if value is in array

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?

Upvotes: 1

Views: 361

Answers (2)

endrcn
endrcn

Reputation: 319

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>

Upvotes: 1

Cyril Gandon
Cyril Gandon

Reputation: 17058

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>

Upvotes: 1

Related Questions