Angularjs过滤以检查值是否在数组

时间:2016-05-23 11:52:37

标签: angularjs

帖子有一个标题和一系列喜欢这篇文章的用户:

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

我正在显示"帖子"像这样:

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

我的控制器doesLike()中有一个函数返回truefalse,具体取决于当前用户的用户名是否在传递给函数的数组中。虽然这种方法有效,但我可以使用过滤器来实现相同的功能,因为我认为这样会更干净吗?

2 个答案:

答案 0 :(得分:1)

我不认为在视图中使用逻辑会更清晰 更清楚的是,不要使用ng-switch通过摘要周期两次调用doesLike函数:

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

答案 1 :(得分:0)

你可以试试这个:

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