带有空字段的AngularJS orderby [英] AngularJS orderby with empty field

查看:25
本文介绍了带有空字段的AngularJS orderby的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在订购我的数据,除了某些字段为空或没有值外,它的工作一切正常.订购时,这些空字段首先出现.例如,在对数字进行排序时,我们会在获取0"值之前得到一个巨大的空列表.

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.

我就是这样做的:

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

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.

推荐答案

我会写一个过滤器,从有序数组中取出名称为空的项目并将它们放在最后:

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>

代码可能如下所示:

.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);
    };
});

工作示例.

顺便说一下,您的小提琴不包含任何相关代码.您是否使用了错误的链接?

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

更新 2:你对我的过滤器的摆弄.

这篇关于带有空字段的AngularJS orderby的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆