OrderBy在AngularJS中没有按预期工作

时间:2015-05-22 12:35:56

标签: javascript json angularjs

我想根据日期以升序显示json对象。为此,我使用OrderBy,但没有按预期工作,它完美地工作到10月,但11月和12月它不工作。

HTML页面:

<li class="row-fluid" style="height: 65px !important;" ng-repeat="item in insertionListItems | index | orderBy: 'insDate': false" ng-class="{'selected': item.$selected}" ng-click="item.$selected = true; onListItemClicked(item)">
    <div class="col-sm-12 cdm-list-item-content">
        <div>
            <span class="col-sm-6" style="padding-left: 0px">{{item.insDate}}</span>
            <span class="col-sm-6" style="padding-left: 0px">{{item.netTotal |number:2}}</span>
        </div>
    </div>
</li>

Json Structure

    insertionListItems  = [
    {
        "index": 0,
        "insDate": "5-4-2015",
        "insName": "Insertion 1",
        "netTotal": -474299.15
    },
    {
        "index": 1,
        "insDate": "6-10-2015",
        "insName": "Insertion 2",
        "netTotal": 1000
    },
    {
        "index": 2,
        "insDate": "1-22-2015",
        "insName": "Insertion 3",
        "netTotal": 100
    },
    {
        "index": 3,
        "insDate": "12-11-2015",
        "insName": "Insertion 4",
        "netTotal": 500
    }
]

1 个答案:

答案 0 :(得分:1)

这里的问题是orderBy过滤器正在排序类似"6-10-2015"的字符串值,但实际上并不是日期对象。因此,正常的字符串比较正在发生,这与日期比较并不完全相同。

因此,如果将“11-21-2014”和“10-21-2014”作为字符串进行比较,则不会给出预期结果。

因此,您必须将每个项目中的日期解析为日期对象,然后才能应用orderBy过滤器。