AngularJS orderby with empty field

前端 未结 9 1751
北海茫月
北海茫月 2020-12-05 13:19

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 n

9条回答
  •  -上瘾入骨i
    2020-12-05 13:51

    In addition to the solution of Klaster_1, add an extra parameter to make the filter more generic:

    http://jsfiddle.net/Zukzuk/JZuCX/27/

    Implementation

    
    

    Filter

    .filter('orderEmpty', function () {
        return function (array, key, type) {
            var present, empty, result;
    
            if(!angular.isArray(array)) return;
    
            present = array.filter(function (item) {
                return item[key];
            });
    
            empty = array.filter(function (item) {
                return !item[key]
            });
    
            switch(type) {
                case 'toBottom':
                    result = present.concat(empty);
                    break;
                case 'toTop':
                    result = empty.concat(present);
                    break;
    
                    // ... etc, etc ...
    
                default:
                    result = array;
                    break;
            }
            return result;
        };
    });
    

    Thnx Klaster_1!

提交回复
热议问题