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

标签 javascript angularjs

我在前端使用 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 中所做的是按评级排序。问题在于,如果属性 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海报

长话短说:

OrderBy 函数将评分最高的元素放在结果的顶部,将带有 ratingposter 的元素放在最后 ===

有什么建议吗?

最佳答案

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

关于javascript - 如何进行过滤器以便将包含 null 属性的结果放在最后?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37364587/

相关文章:

javascript - 用两个值计算价格

javascript - 在 angularJS 上更改页面时设置加载程序

javascript - 添加一个div,其坐标在另一个div中给出

javascript - 验证 url 是否有 pdf 文件

javascript - 从 Firebase 加载数据时,AngularJS 过滤器不起作用

javascript - 相对于初始点击拖动元素

javascript - AngularJS-rize Bootstrap

android - cordova(phonegap)作为应用程序和在 phonegap 应用程序内部工作不同

javascript - 从 AngularJS 对象渲染 html 标签

javascript - 在 Angular 服务/ Controller 中实现安全 $apply 的最佳方法