通过Angular Directive按顺序显示数月

时间:2013-12-10 23:45:57

标签: javascript angularjs iterator angularjs-directive

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之外轻松完成这项工作,但我正努力在他们的系统中工作。也许是一个自定义指令?

2 个答案:

答案 0 :(得分:1)

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

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

DEMO

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

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

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

答案 1 :(得分:0)

难道你不能只改变你的数据结构,所以你要迭代一个包含你需要的所有信息的数组吗?像这样:

$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..
];