Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS orderby with empty field

I am ordering a my data and its working all correcty except some fields are empty or have no value. When ordered these empty field come up first. For example when ordering numbers we would get a huge empty list before getting the "0"-values.

I am doing it like thise:

ng-click="predicate = 'name'; reverse=!reverse"

and

ng-repeat="name in names | orderBy:predicate:reverse"

JSFiddle: http://jsfiddle.net/JZuCX/1/

Is there an easy elegant way to fix this? I want the empty fields to come last, no matter what.

like image 801
deekay Avatar asked Sep 04 '13 02:09

deekay


2 Answers

How about this for sorting strings:

item in (items|orderBy:['!name', 'name'])

The advantage (apart from being more concise) is it sorts null & undefined with the blank strings.

In my case I wanted the blanks & nulls & undefineds together at the top (nulls and undefineds by default sort to the bottom), so I used:

item in (items|orderBy:['!!name', 'name'])
like image 191
Sean Avatar answered Nov 04 '22 09:11

Sean


I'd write a filter that takes items with empty name from ordered array and places them at the end:

<li ng-repeat="item in (items|orderBy:'name'|emptyToEnd:'name')">{{item.name}}</li>

Code might look like this:

.filter("emptyToEnd", function () {
    return function (array, key) {
        if(!angular.isArray(array)) return;
        var present = array.filter(function (item) {
            return item[key];
        });
        var empty = array.filter(function (item) {
            return !item[key]
        });
        return present.concat(empty);
    };
});

Working example.

By the way, your fiddle doesn't contain any relevant code. Did you use the wrong link?

Update 2: Your fiddle with my filter.

like image 43
Klaster_1 Avatar answered Nov 04 '22 07:11

Klaster_1