簡體   English   中英

AngularJS:如何將數據獲取到對象和數組中?

[英]AngularJS: how do i get data into an object and array?

我試圖從電子表格中獲取數據到數組。 我已經將數據存儲在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,它完美地調用了它。 在我的console上的inspect元素上,我得到錯誤:'Uncaught 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;

當你調用this它是指jQuery的。 因此parts不存在。

另外,您做錯了。 您應該為此使用服務,並且該服務中有一個angular的$http用於處理ajax請求。

您使用的方式不正確。

在這里閱讀: https : //docs.angularjs.org/guide/services

您需要使用空的Array對象初始化this.parts變量:

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
    });
};

您也可以使用Array的push方法代替this.parts[i] = ...

this.parts.push({"id": id, ... });

你有沒有嘗試過 :

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};  

這樣最終只會為數組分配一個值。每次數組都會更新最新值並刪除以前的值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM