AngularJS:我如何将数据导入对象和数组?

时间:2016-03-23 11:11:55

标签: javascript arrays angularjs json

我正在尝试将数据从电子表格中导入数组。我已经将数据存储在javascript变量中。但现在我需要将这些varriables存储为我的数组中的一个obect。这是我的代码:

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,它完美地调用它。在我的控制台上检查元素我得到错误:'未捕获TypeError:无法设置属性'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]
}

编辑:在我的控制器下初始化的数组部分就像这样

var parts = [];

并在我的控制器中声明为

this.parts = parts;

3 个答案:

答案 0 :(得分:1)

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

另外,你做错了。您应该为它使用服务,并且在服务中有一个用于处理ajax请求的角度$http

以你的方式,你没有正确使用角度。

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

答案 1 :(得分:0)

您需要使用空Array对象初始化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); this.parts = []; // <-- this line was added // skipped }); }; 变量:

push

此外,您可以使用数组的this.parts[i] = ...方法代替this.parts.push({"id": id, ... });

{{1}}

答案 2 :(得分:0)

你试过了吗?

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

因为:

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

这将最终仅为array分配一个值.Everytime数组将获得最新值并删除以前的值。