我有简单的月份表,有一些数据但不完整。缺少几个月因此很难与每个月的确切匹配。这些数据必须与确切的月份相匹配,我在JSON中指定的月份是“2015-01”,“2015-02”,“2015-03”......格式。但也无序。 Plunker:http://plnkr.co/edit/rW36ckdEfWW7qDqeYiK8?p=preview
$scope.year = [
{"month":"2015-03", "val":"23"},
{"month":"2015-02", "val":"45"},
{"month":"2015-06", "val":"11"},
{"month":"2015-01", "val":"56"},
{"month":"2015-11", "val":"11"},
{"month":"2015-12", "val":"15"}
];
帮我将月份值精确地放在特定月份以下。
答案 0 :(得分:2)
只需使用orderBy。 <td ng-repeat="item in year | orderBy: 'month'">
。它将以ng-repeat对您的数据进行排序。
但这是您的数据的问题。你有空的月份。你必须填写它们。
答案 1 :(得分:1)
item in year | orderBy: 'month'
会缩短您的JSON,但您每个月都不会获得td
。因此,您需要一些算法来代替此解决方案。
[["56",1],["45",2],["23",3],["11",6],["11",11],["15",12]]
[{"month":1,"val":"56"},{"month":2,"val":"45"},{"month":3,"val":"23"},{"month":4,"val":0},{"month":5,"val":0},{"month":6,"val":"11"},{"month":7,"val":0},{"month":8,"val":0},{"month":9,"val":0},{"month":10,"val":0},{"month":11,"val":"11"},{"month":12,"val":"15"}]
经过一番思考后我想出了这个:
app.controller("myCtrl", function($scope){
var arr = [];
var year = [
{"month":"2015-03", "val":"23"},
{"month":"2015-02", "val":"45"},
{"month":"2015-06", "val":"11"},
{"month":"2015-01", "val":"56"},
{"month":"2015-11", "val":"11"},
{"month":"2015-12", "val":"15"}
];
var ob = [], temp = [];
for(var i=0;i<year.length;i++){
ob.push([year[i].val, parseInt(year[i].month.split('-')[1])]);
}
ob.sort(function(a, b) {return a[1] - b[1]})
var counter=0;
for(var i=0; i<12; i++){
if(ob[counter][1] == (i+1)){
temp.push({month:ob[counter][1],val:ob[counter][0]})
counter++;
} else{
temp.push({month:(i+1),val:0})
}
}
$scope.year = temp;
});