在我的情况下如何使用AngularJs显示数组?

时间:2014-10-30 06:05:07

标签: javascript angularjs

我有一个类似以下的javascript数组:

var array = [
   2005 = [
       Jan = [0,1,2,3,5...],
       Feb = [0,1,2,3,5...],
       ...more
   ], 
   2006 = [
       Jan = [0,1,2,3,5...],
       Feb = [0,1,2,3,5...],
       ...more
   ], 
   2007 = [
       Jan = [0,1,2,3,5...],
       Feb = [0,1,2,3,5...],
       ...more
   ]

]

$scope.cal = array;

我正在尝试使用ng-repeat

构建日历
<div ng-repeat = "year in cal">
    {{year}}
</div>

没有输出,我收到错误

Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. 
Repeater: year in cal, Duplicate key: undefined:undefined, Duplicate value: undefined

我不确定我做错了什么,我的大脑是油炸的。请帮我解决这个问题。谢谢!

3 个答案:

答案 0 :(得分:1)

您需要在可绑定的不同年份条目之间使用公共属性。因此,您需要某种值属性,该属性包含年份或月份等标识符以及包含值数组的另一个属性。请参阅下面的示例。

var myApp = angular.module('myApp', []);

myApp.controller('MyCtrl', function ($scope) {
    $scope.cal = [
        {
            value: 2005,
            month:
            [
                {
                    value: 'Jan',
                    days: [0, 1, 2, 3]
                },
                {
                    value: 'Feb',
                    days: [0, 1, 2, 3]
                }
            ]
        },
        {
            value: 2006,
            month:
            [
                {
                    value: 'Jan',
                    days: [0, 1, 3, 7]
                },
                {
                    value: 'Feb',
                    days: [0, 1, 2, 3]
                }
            ]
        }
    ];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
    <div ng-controller="MyCtrl">
      <div ng-repeat = "year in cal">
          Year: {{year.value}}
          <div ng-repeat = "month in year.month">
              Month: {{month.value}}
              <div ng-repeat = "day in month.days">
                Day: {{day}}
              </div>
          </div>
      </div>
    </div>
</div>

答案 1 :(得分:1)

检查工作弹药here

除了JSON对象的语法问题外,设计应该是这样的:

    [
        {
           yearNum: 2005,
           months: [
                        {Jan : [0,1,2,3,5]},
                        {Feb : [0,1,2,3,5]},
                      ]
        }, 
        {
           yearNum: 2006,
           months: [
                        {Jan : [0,1,2,3,5]},
                        {Feb : [0,1,2,3,5]},
                      ]
        }
    ]

答案 2 :(得分:0)

尝试像这样格式化数组。

var array = [
   { 2005: [
      { Jan: [0, 1, 2, 3, 5] },
      { Feb: [0, 1, 2, 3, 5] },
   ]
}];