简体   繁体   English

使用时间和Angular.js对对象数组进行排序

[英]Sorting array of objects using time and Angularjs

I want to sort my array of objects in order from earliest to latest in time. 我想按从最早到最新的顺序对对象数组进行排序。 I used the momentjs library to do this at first and it worked, but the method I was using is now deprecated. 我最初是使用momentjs库执行此操作的,但现在可以使用,但是现在不推荐使用我使用的方法。

At first I tried making the input time into a standard time(ex: 0500) and then sort it using that property. 首先,我尝试将输入时间设为标准时间(例如0500),然后使用该属性对其进行排序。 But I had trouble pushing this new standard time and all the other properties into the plans array. 但是我很难将这个新的标准时间和所有其他属性推入计划数组。

I was thinking of using array.sort() and sort it first by am/pm and then by number. 我当时在考虑使用array.sort()array.sort() am/pm对其进行排序,然后再按数字对其进行排序。 I'm not sure how to go about it since I have to deal with am and pm 我不确定该怎么做,因为我必须处理ampm

app.js app.js

.controller('SchedulerController', schedulerCtrl);

    function schedulerCtrl() {
        this.plans = [
        {
            displayTime: '05:00pm',
            duration: '30',
            task: 'Team meeting',
        },
        {
            displayTime: '06:00pm',
            duration: '60',
            task: 'Watch favorite TV show'
        }
        ];
    }
    schedulerCtrl.prototype.addNewTask = function() {
        var that = this;
        that.plans.push(that.user);
        that.user = '';

}

you can use underscorejs for an efficient sorting . 您可以使用underscorejs进行有效的排序

schedulerCtrl.prototype.addNewTask = function() {
        var that = this;
        that.plans.push(that.user);
        _.sortBy(that.plans, function (item) { return item.displayTime });
        that.user = '';

}

custom filter can be used , 可以使用自定义过滤器,

<p>{{item | orderBy:sortItemsAccording2Time}}</p>


var App = Angular.module('myApp',[])
 App.filter('sortItemsAccording2Time',function(input,scope){
    //logic here  (service dependency can also be used for orderby service by just injecting the respective service which serves the job)
 })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM