我在前端使用 Angular,我正在尝试弄清楚如何执行过滤器以便将包含 2 个属性的结果放在最后。可以是一个或另一个属性。
例如:
<div ng-repeat="show in shows | filter:query | orderBy:'rating':true">
<a href="/shows/{{show._id}}">
<img ng-src="{{show.poster}}" width="100%"/>
</a>
<div>
<a href="/shows/{{show._id}}">{{show.name}}</a>
<p>
Episodes: {{show.episodes.length}} <br>
<span>Rating: {{show.rating}}</span>
</p>
</div>
</div>
如您所见,我在 HTML 中所做的是按评级排序。问题在于,如果属性 rating
为 null
,则该元素将位于结果的顶部,然后具有最高评级的元素出现在列表中如我所愿。
这是我收到的对象:
{
"_id": 310243,
"name": "Five Star Babies: Inside the Portland Hospital",
"airsDayOfWeek": "Wednesday",
"airsTime": "21:00",
"firstAired": "2016-04-13T00:00:00.000Z",
"network": "BBC Two",
"overview": "An exclusive glimpse inside the UK's only private maternity hospital.\r\n",
"rating": null, // THIS PROPERTY COMES NULL
"ratingCount": 0,
"status": "Continuing",
"poster": "/someImage/path",
"subscribers": []
}
对象来自这里:
$scope.shows = Show.query();
$scope.shows
返回这个:
[
{
"_id": 73787,
"name": "That '70s Show",
"airsDayOfWeek": "Thursday",
"airsTime": "8:00 PM",
"firstAired": "1998-08-23T00:00:00.000Z",
"network": "FOX (US)",
"overview": "Set in the Wisconsin suburbs...",
"rating": null, // PROPERTY NULL
"ratingCount": 87,
"status": "Ended"
"poster": "/some/Img/Path"
},
{
"_id": 35345,
"name": "Friends",
"airsDayOfWeek": "Thursday",
"airsTime": "8:00 PM",
"firstAired": "1998-08-23T00:00:00.000Z",
"network": "FOX (US)",
"overview": "New York TV Show...",
"rating": 9.1,
"ratingCount": 87,
"status": "Ended"
"poster": null // PROPERTY NULL
}
]
这就是对象出现的方式,以及我需要放在结果末尾的 2 个属性,以防它们出现 null
、rating
或 海报
。
长话短说:
OrderBy 函数将评分最高的元素放在结果的顶部,将带有 rating
或 poster
的元素放在最后 === 空
有什么建议吗?
最佳答案
您可以编写自己的自定义 orderBy
函数,它会返回一个值。例如:
$scope.order = function(show) {
if (show.rating == null || show.poster == null) return 0;
return show.rating;
}
HTML
<div ng-repeat="show in shows | filter:query | orderBy:order:true">
关于javascript - 如何进行过滤器以便将包含 null 属性的结果放在最后?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37364587/