2015-09-23 378 views
1

我一直在这里呆了几天,我只能承认我对这件事缺乏认识。 我有一个我从$ http请求收到的文章数组,并通过调用sortArticles(文章)迭代到以下结构中。原因是为了简化httpData对象的结构并摆脱一些嵌套数组(我已经删除了一些可读性的代码)。ng-repeat对json对象嵌套的json

article.service.js:

function sortArticles(httpData){ 
    var sortedList = []; 
    for(var i = 0; i < httpData.length; i++){ 
     var date = new Date(httpData[i].Date); 
     var tmpObj = {Name: httpData[i].Name, 
         Price: httpData[i].Price, 
         Date: date}; 
     // I want my controller to receive a list with all articles 
     // linked to a specific date in the same array. Reason being; 
     // Each date will become a tab in the view: 
     if(typeof sortedList[date] == "undefined"){ 
      sortedList[date] = []; 
      sortedList[date][0] = tmpObj; 
     }else{ 
      sortedList[date][sortedList[date].length] = (tmpObj); 
     } 

    } 
    return sortedList; 
} 

现在我控制器接受上述排序列表如下:

article.controller.js:

angular 
.module('app') 
.controller('ArticleController', ArticleController); 

ArticleController.$inject = ['articleservice']; 

function ArticleController(articleservice) { 

    var vm = this; 
    articleservice.getArticles() 
     .then(function(data){ 
      vm.sortedList = data; 
      for(var i in vm.sortedList){ 
       console.log("i: ", i, " ### vm.sortedList[i]: ", vm.sortedList[i] + "\n"); 
      } 
     }, 
     function(reason){ 
      console.log(reason); 
     }) 
     .catch(function(err){ 
      console.log(err); 
     }); 
} 

在控制台.log()高于一切都在浏览器的控制台中显示,如下所示:

i:W ed Sep 02 2015 ### vm.articles [i]:[object Object],[object Object] ....等 i:Wed Sep 03 2015 ### vm.articles [i]:[object Object], [对象对象] ....等

这对我来说是一个阵列工作的证明。

但我该如何用ng-repeat呈现这个角? 我只是得到了一个空白页面的所有下面的尝试:

<span ng-repeat="(key, value) in vm.sortedList">{{key}}</span> 


<span ng-repeat="(key, value) in vm.sortedList">{{value[key]}}</span> 

<div ng-repeat="(key, value) in vm.sortedList"> 
    <div ng-repeat="article in value[key]">{{article.Name}}</div></div> 

半伪代码的最终目标是这样的

<md-tab ng-repeat="date in vm.sortedList" label: {{date}}> 
     <tabContent> 
      <p ng-repeat="article in date"> 
        <table> 
         <tr> 
          <th>Name</th> 
         </tr> 
         <tr>article.name</tr> 

...等等等等

请帮我上网,你是我唯一的希望

+0

哪里出了问题是什么呢?安慰。请记录数组以查看它是否为所需的结构,如果在打印变量时添加了{{}}或ng-bind,则在得到正确结果后,“半伪”代码部分将非常正确。 –

+0

嗯,它只是不起作用。页面是空白的。我试图重新创建这个小提琴,我想并希望我没有在这里犯一个愚蠢的错误:http://jsfiddle.net/hhyz3yqh/1/ –

+0

看看答案下面,你不能迭代通过以字符串作为键的数组。用整数替换日期,你会注意到它的工作原理。建议创建一个对象,如{date:date,[obj1,obj2]}或类似的东西。 –

回答

1

在JavaScript数组中,索引必须是整数。

以下:

vm.sortedList = []; 
var date = "May 2015"; 
vm.sortedList[date] = []; 

将一个名为May 2015属性添加到sortedList,它不会推动任何东西放入数组。如果你记录它,你可以看到sortedList的长度仍然是0

所以下面:

<p ng-repeat="dates in vm.sortedList"> 

将遍历一个空数组。

使用对象来代替:

vm.sortedList = {};

,并使用以下遍历它:

ng-repeat="(key,value) in vm.sortedList"

演示:http://jsfiddle.net/Lka8qx4m/

+0

我们有,非常感谢! –

+0

不客气:) – tasseKATT