通过Angular Directive按顺序显示月份

Getting months to display in order in through Angular Directive

本文关键字:显示 顺序 Angular Directive 通过      更新时间:2024-07-04

jsFiddle

我正在尝试使用Angular的ng repeat指令构建一个表,该指令显示两年的数据:

--------------------------------------------------------
January  |  jan text this year   |  jan text last year  
February |  feb text this year   |  feb text last year  
March    |  march text this year |  march text last year
--------------------------------------------------------

我最终得到的是:

--------------------------------------------------------
January  |  feb text this year   |  feb text last year  
February |  jan text this year   |  jan text last year  
March    |  march text this year |  march text last year
--------------------------------------------------------

我有一个有两年数据的物体。

$scope.data = {
    thisYear: {
        January: 'jan text this year',
        February: 'feb text this year',
        March: 'march text this year'
        // etc..
    },
    lastYear: {
        January: 'jan text last year',
        February: 'feb text last year',
        March: 'march text last year'
        // etc..
    }
};

以及一个简单的阵列:$scope.months = ['January', 'February', 'March'];

几个月很容易,工作也很好:

<div ng-repeat="month in months">{{ month }}</div>

然而,数据并没有按预期工作:

<div ng-repeat="d in data.thisYear">{{ d || "none" }}</div>

数据按字母顺序迭代,这意味着当月的数据不一致。由于Angular数据绑定不允许使用基元类型,所以我无法用多维数组来解决它。

我觉得我忽略了一些愚蠢和微小的事情,我知道在Angular之外我可以很容易地完成这件事,但我正在努力在他们的系统中工作。也许是自定义指令?

您可以通过循环月来完成每一列

<div ng-repeat="month in months">{{ data.lastYear[month] || "none" }}</div>

演示

就我个人而言,我会将数据重组为类似的东西

[{year: 2013, months:[{month: 'val', text:'val'},{month: 'val', text:'val'}....]},{ year: 2012:.....}]

您关于无法对数组执行此操作的评论偏离了轨道。对象没有顺序,而数组有

难道你不能改变你的数据结构,让你在一个包含你需要的所有信息的数组上迭代吗?类似这样的东西:

$scope.data = [
    { month: 'January', thisYear: 'jan text this year', lastYear: 'jan text last year' },
    { month: 'February', thisYear: 'feb text this year', lastYear: 'feb text last year' },
    { month: 'March', thisYear: 'mar text this year', lastYear: 'mar text last year' },
    // etc..
];