帖子有一个标题和一系列喜欢这篇文章的用户:
{
"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()
中有一个函数返回true
或false
,具体取决于当前用户的用户名是否在传递给函数的数组中。虽然这种方法有效,但我可以使用过滤器来实现相同的功能,因为我认为这样会更干净吗?
答案 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>