在ng-repeat中不显示嵌套JSON

Nested JSON not display in ng-repeat

本文关键字:嵌套 JSON 显示 ng-repeat      更新时间:2023-09-26

我在使用ng-repeat指令访问嵌套JSON时遇到麻烦。我知道它正在工作,因为JSON对象的未嵌套部分正在显示。

下面是我的代码:http://plnkr.co/edit/V2iURMa8t7vG9AqDFMOf?p=preview

JavaScript:

var app = angular.module("app", [ ]);
app.controller("AppTest", function($scope){
$scope.currentInfo=[{"id":0,"article":"JavaScript Conquers the World","publisher":"Daily Times","meta_data":{"comments":4}},
  {"id":1,"article":"The Problem with Foobar","publisher":"New York Times","meta_data":{"comments":27}}];
$scope.tableInfo=[{"name":"id","dataType":"Integer","isEditable":false},
  {"name":"article","dataType":"String","isEditable":true},
  {"name":"publisher","dataType":"String","isEditable":false},
  {"name":"meta_data.comments","dataType":"Integer","isEditable":false}];
});
HTML:

 <body ng-app="app" ng-controller="AppTest as app"
  <table>
    <tbody ng-repeat="anotherItem in currentInfo">
      <tr>
        <td ng-repeat="item in tableInfo">{{anotherItem[item.name]}}</td>
      </tr>
    </tbody>
  </table>
 </body>

另一个更好的解决方案是在控制器中添加将为您解析值的函数。你的解决方案的问题是,你需要Angular解析meta_data.comments,但它把它当作数组查找中使用的字符串来处理,因为它已经解析了item.name.

$scope.resolveLookup = function(object, lookup) {
    var depth = lookup.split('.').length;
    var currentObj = object;
    for(var x=0; x<depth; x++) {
      currentObj = currentObj[lookup.split('.')[x]];
    }
    return currentObj;
};

然后把HTML改成:

<td ng-repeat="item in tableInfo">{{resolveLookup(anotherItem,item.name)}}</td>

这是Plunker: http://plnkr.co/edit/RVd2ncwstyQtCtdhcC9U?p=preview

问题是它将'metadata.comments'放在[]中,它没有意识到它需要再次由angular解决。如果不改变'tableInfo'对象的数据结构,我想不出解决办法。

我是这样做的。

修改table info为:

 $scope.tableInfo = [{
    "name": ["id"],
    "dataType": "Integer",
    "isEditable": false
  }, {
    "name": ["article"],
    "dataType": "String",
    "isEditable": true
  }, {
    "name": ["publisher"],
    "dataType": "String",
    "isEditable": false
  }, {
    "name": ["meta_data", "comments"],
    "dataType": "Integer",
    "isEditable": false
  }];

把你的HTML改成:

      <td ng-repeat="item in tableInfo" ng-if="item.name.length==1">{{anotherItem[item.name[0]]}}</td>
      <td ng-repeat="item in tableInfo" ng-if="item.name.length==2">{{anotherItem[item.name[0]][item.name[1]]}}</td>

这是Plunker: http://plnkr.co/edit/q9lHZ2TD7WZ74b2f6Ais?p=preview