这是我的prg-ctrl.js
:
$scope.getDataOfProject = function(project, year){
var projectData = project.data[year];
var smthData = [];
for (var i = 1; i <= 12; i++) {
if (projectData[i]) {
smthData.push(projectData[i]);
} else {
smthData.push(0);
}
}
return smthData;
};
这里是JSON的片段:
"projects": [
{
"id": 1,
"data": {
"2016": {
"12": 18
},
"2017": {
"1": 17.6,
"2": 10.1,
"3": 33.3,
"4": 4.30
}
},
.......
然后在prj.html
文件中我有ng-repeat
:
<div class="col-md-9">
<div ng-repeat="entity in getDataOfProject(project, 2016)">{{entity}}</div>
</div>
但我的<div class="col-md-9">
仍然是空的。但是,当我把smth像:
<div class="col-md-9">
<div>{{getDataOfProject(project, 2016)}}</div>
</div>
我可以看到我的数据。我做错了什么?
答案 0 :(得分:1)
问题与数组结果中可能存在重复的事实有关,因此您可能会在控制台中看到警告(或错误)。为避免这种情况,请使用track by
:
<div class="col-md-9">
<div ng-repeat="entity in getDataOfProject(project, 2016) track by $index">{{entity}}</div>
</div>
另外,请确保正确检查原始对象中是否存在密钥:
$scope.getDataOfProject = function(project, year){
if (typeof(project.data[year]) === "undefined") {
return [];
}
var projectData = project.data[year];
var smthData = [];
for (var i = 1; i <= 12; i++) {
if (projectData[i]) {
smthData.push(projectData[i]);
} else {
smthData.push(0);
}
}
return smthData;
};