tommyd456 tommyd456 - 2 years ago 85
AngularJS Question

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">
<span ng-show="doesLike(post.likes)">Liked already</span>
<span ng-hide="doesLike(post.likes)">Like this post</span>

and I have a function in my controller
that returns
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?

Answer Source

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">
    <span ng-switch="doesLike(post.likes)">
        <span ng-switch-when="true">
            Liked already
        <span ng-switch-default>
            Like this post
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download