TheUnnamed TheUnnamed - 6 months ago 6
AngularJS Question

How to do a filter in order to put at the end the results containing a null property?

I am working with Angular in the frontend and I am trying to figure out how to do a filter in order to put at the end the results containing 2 properties in null. Could be one or the other property.

For example:

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


What I am doing in the HTML, is ordering by rating as you can see. The problem is that if the property
rating
comes
null
, then that element will be at the top of the results, and then the elements with the highest rating comes in the list just as I want.

This is the object I am receiving:

{
"_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": []
}


The object comes from here:

$scope.shows = Show.query();


and that
$scope.shows
returns this:

[
{
"_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
}
]


That's the way the object comes, and those the 2 properties that I need to put at the end of the results in case they come
null
,
rating
or
poster
.

TL;DR:

OrderBy function which puts at the top of the results the elements with the highest ratings, and at the end the elements with
rating
or
poster
===
null


Any suggestions?

Answer

You can write your own custom orderBy function which returns a value. For example:

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

Comments