我想在特定月份没有可用数据时填写空白值。这是plunker .. http://plnkr.co/edit/f0IklkUfX8tkRZrn2enx?p=preview
$scope.year = [
{"month":"mar", "val":"23"},
{"month":"feb", "val":"45"},
{"month":"jan", "val":"56"}
];
var total = ["jan", "feb", "mar", "apr", "may", "jun", "aug", "sep", "oct", "nov", "dec"];
for(var i=0; i<total.length; i++){
if($scope.year[i].month === undefined){ //logic here to see absent month.
$scope.year.push(
{
"month":total[i],
"val":"0"
})
}
}
我创建了一系列默认的总月份项目,用于比较预期对象中的每个月项目,如果项目在预期对象中不存在,则需要在预期对象本身中创建空项目或值为“0”。
答案 0 :(得分:2)
您可以执行以下操作
Js更新
var year = [
{"month":"mar", "val":"23"},
{"month":"feb", "val":"45"},
{"month":"jan", "val":"56"}
];
var total = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
// Current months array
var currentMonth = [];
angular.forEach(year, function(item){
currentMonth.push(item.month);
});
// iterating over months
for(var i=0; i<total.length; i++){
//$scope.year = [];
// checking if month is absent
if(currentMonth.indexOf(total[i]) === -1){ //logic here to see absent month.
year.push(
{
"month":total[i],
"val":"0",
"order" : i
})
} else {
year[currentMonth.indexOf(total[i])].order = i; // adding order
}
}
$scope.year = year;
<强>标记强>
<!-- Order by new property order -->
<td ng-repeat="item in year | orderBy: 'order'">
{{item.val}}
</td>
答案 1 :(得分:0)
year [i]未定义,因此您尝试获取不存在的对象字段。 试试“if($ scope.year [i] === undefined)”
答案 2 :(得分:0)
您使用orderBy
的想法根据month
无法正常工作,因为您并不是在寻找按字母顺序排列的类型。
以下创建数据中存在的月份数组。然后它会在一年中的所有月份循环并添加缺失的数据。最后根据月份索引对数据进行排序
// create array of months available in data
var availableMonths = $scope.year.map(function(item){
return item.month;
});
// loop over all months and if it doesn't exist in data add it
total.forEach(function(mo){
if(availableMonths.indexOf(mo) ===-1 ){
$scope.year.push({"month":mo, "val":"0" })
}
});
// sort data using index of months
$scope.year.sort(function(a,b){
return total.indexOf(a.month) > total.indexOf(b.month);
});
删除html中的orderBy
过滤器,因为数据已经排序
步骤2&amp;上面的3实际上可以组合到splice()
数组,所以最终的顺序是正确的但为了便于理解我将它们作为单独的操作留下了
的 DEMO 强>
答案 3 :(得分:0)
试试这个。
$scope.year = [ {"month":"jan", "val":"56"}, {"month":"feb", "val":"45"}, {"month":"mar", "val":"23"} ]; var total = ["jan", "feb", "mar", "apr", "may", "jun", "aug", "sep", "oct", "nov", "dec"]; for(var i=0; i<total.length; i++){ if(!$scope.year[i] || $scope.year[i].month === undefined){ $scope.year.push( { "month":total[i], "val":"0" }) } }