gpt4 book ai didi

javascript - AngularJS:如何将数据获取到对象和数组中?

转载 作者:行者123 更新时间:2023-12-03 07:22:06 25 4
gpt4 key购买 nike

我正在尝试将电子表格中的数据放入数组中。我已经将数据存储在 javascript 变量中。但现在我需要将这些变量作为对象存储在我的数组中。这是我的代码:

this.json = function(){
jQuery.getJSON("http://cors.io/?u=https://spreadsheets.google.com/feeds/list/1l4XTKaLZihj5WDRuZJE5Y7RQ7Cr7SD_-tH0ctwhizWc/od6/public/values?alt=json").success(function(data) {
console.log(data.feed.entry);
//try
for (var i = 0; i < data.feed.entry.length; i++) {

var id = data.feed.entry[i].gsx$id.$t;
var name = data.feed.entry[i].gsx$name.$t;
var price = data.feed.entry[i].gsx$price.$t;
var notcompatiblewith = data.feed.entry[i].gsx$notcompatiblewith.$t;

this.parts[i] = {"id": id, "name": name, "price": price, "comp": notcompatiblewith, "canAdd": true, "added": false};
};
});
};

我在 html 中使用 ng-init="myctrl.json()"调用函数 this.json ,它完美地调用了它。在检查元素的控制台中,我收到错误:“未捕获类型错误:无法设置未定义的属性“0””

如果初始化良好,我的数组应该如下所示:

{
id: 1,
name: 'vitamine A',
price: 3,
canAdd: true,
added: false,
comp: [2, 5]
},
{
id: 2,
name: 'vitamine B',
price: 5,
canAdd: true,
added: false,
comp: [1, 3]
},
{
id: 3,
name: 'vitamine C',
price: 2,
canAdd: true,
added: false,
comp: [2]
},
{
id: 4,
name: 'Opium',
price: 20.95,
canAdd: true,
added: false,
comp: []
},
{
id: 5,
name: 'steroids',
price: 12.5,
canAdd: true,
added: false,
comp: [1]
}

编辑:数组部分在我的 Controller 下初始化,如下所示

var parts = [];

并在我的 Controller 中声明为

this.parts = parts;

最佳答案

当你调用this时,它指的是jQuery。因此 parts 不存在。

还有,你的做法是错误的。您应该为其使用一个服务,并且在该服务中有一个 Angular 的 $http 用于处理 ajax 请求。

以您的方式,您没有正确使用 Angular 。

阅读此处:https://docs.angularjs.org/guide/services

关于javascript - AngularJS:如何将数据获取到对象和数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36176573/

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