2016-12-02 65 views
-1

我有這樣的代碼AngularJS服務裏面:JSON迭代工作中途

var products = []; 

$http.get('http://www.......it/app/parse.php'). 
    success(function(data, status, headers, config) { 
     products.push(data); 
     console.log(products); 
    }). 
    error(function(data, status, headers, config) { 
     console.error("Error JSON") 
     console.log(data); 
}); 

return { 
    all: function() { 
     return products; 
    }, 
    remove: function(chat) { 
     products.splice(products.indexOf(chat), 1); 
    }, 
    get: function(chatId) { 
     for (var i = 0; i < products.length; i++) { 
      if (products[i].id === parseInt(chatId)) { 
       return products[i]; 
      } 
     } 
     return null; 
    } 
}; 

的HTML由JSON日誌和NG-重複。

<pre>{{shoesItems.items | json}}</pre> 
<div class="row" ng-repeat="item in shoesItems.items"> 

這是結果:

enter image description here

雖然如果我改變products.push(data);products.push(data[0]);我看到的第一個圖像:

enter image description here

我該如何告訴他們所有?

回答

0

由於對這個答案的評論說,這是行不通的,因爲那時我們失去了參考原來的產品陣列。試試這個:

products.push.apply(products, data)

基本上,它增加了對數據的產品陣列中的所有元素。

+0

對,這是因爲角度不會在每個摘要循環中調用'.all()',因此如果更改產品參考,則會丟失。然後調用'.push()',但循環遍歷所有數據。或者有一種方法可以在不改變ref的情況下用'products.push.apply(products,data)'來進行連接 – olivarra1

1

你的第一個結果是數組的數組,嘗試訪問的第一個對象就是這樣,

<pre>{{shoesItems[0].items | json}}</pre> 
<div class="row" ng-repeat="item in shoesItems[0].items">