无法从json填充html表

时间:2014-07-23 21:02:34

标签: javascript json angularjs

请帮助我填写json回复表:

[
  {
    "id": 1,
    "firstName": "James",
    "nickNames": [
      {}
    ]
  },
  {
    "id": 2,
    "firstName": "Linda",
    "nickNames": [
      {
        "id": 2,
        "name": "lin"
      },
      {
        "id": 3,
        "name": "l1n"
      },
      {
        "id": 1,
        "name": "Lin"
      }
    ]
  }
]

我正试图填写这样的表:

<table id="users" class="table table-striped table-hover">
  <thead>
  <tr>
    <th>#</th>
    <th>Name</th>
    <th>Nicknames</th>
  </tr>
  </thead>
  <tbody>
  <tr>
    <td>1</td>
    <td>James</td>
    <td>none</td>
  </tr>
  <tr>
    <td>2</td>
    <td>Linda</td>
    <td>lin, l1n, Lin</td>
  </tr>
  </tbody>
</table>

我已经做了什么:

'use strict';

angular.module('myAppControllers', [])
  .controller('UserCtrl', ['$scope', 'User', function ($scope, User) {
    User.query().$promise.then(function (data) {
        $scope.users = data;
      }, function (reason) {
        console.log('Failed: ' + reason)
      }
    )
  }]);

这是我的模板:

<div class="row">
  <div class="page-header">
    <h1>Users</h1>
  </div>
  <table class="table table-striped table-hover">
    <thead>
    <tr>
      <th>#</th>
      <th>Name</th>
      <th>Nicknames</th>
    </tr>
    </thead>
    <tbody>
    <tr ng-repeat="user in users | orderBy:'id' track by user.id">
      <td>{{ user.id }}</td>
      <td>{{ user.firstName }}</td>
      <td ng-repeat="nickname in user.nickNames | emptyUser">{{ nickname.name }}</td>
    </tr>
    </tbody>
  </table>
</div>

嵌套数组的问题我无法将条目拆分为一个<td>标记。

P.S。我无法改变服务器的api。

我在StackOverflow上看到了类似的问题,但它们与我的问题不同。

2 个答案:

答案 0 :(得分:2)

不要在td代码上重复 - 在span中使用td

<td><span ng-repeat="nickname in user.nickNames | emptyUser">{{ nickname.name }} </span></td>

答案 1 :(得分:0)

请参见此处:http://jsbin.com/vined/1/edit

  <table class="table table-striped table-hover">
    <thead>
    <tr>
      <th>#</th>
      <th>Name</th>
      <th>Nicknames</th>
    </tr>
    </thead>
    <tbody>
    <tr ng-repeat="user in data | orderBy:'id' track by user.id">
      <td>{{ user.id }}</td>
      <td>{{ user.firstName }}</td>
      <td><p ng-repeat="nickname in user.nickNames | emptyUser ">{{ nickname.name }}</p></td>
    </tr>
    </tbody>