gpt4 book ai didi

javascript - 我如何解析 ng-repeat 内的数组(来自函数)

转载 作者:行者123 更新时间:2023-12-03 05:20:05 27 4
gpt4 key购买 nike

这是我的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">仍然是空的。但是当我这样写时:

<div class="col-md-9">
<div>{{getDataOfProject(project, 2016)}}</div>
</div>

我可以看到我的数据。我做错了什么?

最佳答案

该问题与数组结果中可能存在重复项有关,因此您可能会在控制台中看到警告(或错误)。为了避免这种情况,请使用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;
};

关于javascript - 我如何解析 ng-repeat 内的数组(来自函数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41427995/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com