如何进行过滤以便将包含null属性的结果放在最后?

时间:2016-05-21 15:07:58

标签: javascript angularjs

我正在使用前端的Angular,我正在试图弄清楚如何进行过滤,以便最后将包含2个属性的结果放在null中。可能是一个或另一个属性。

例如:

    <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中所做的是按照您所看到的等级进行排序。问题是如果属性ratingnull,那么该元素将位于结果的顶部,然后具有最高评级的元素将按照我的意愿出现在列表中。

这是我收到的对象:

{
  "_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个属性nullrating或{{1} }。

TL; DR:

OrderBy函数,在结果的顶部放置具有最高评级的元素,最后在元素posterrating === poster

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

您可以编写自己的自定义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">

Sample pen