在对象中使用ng-repeat - array时,布局是不同的

时间:2017-10-03 22:58:51

标签: css angularjs html5

我有一个用户对象,它具有不同的属性,如名称,电子邮件等。除此之外,它还包含一个指定用户角色的数组。我的问题是当我迭代该数组时,如果它只有一个值,它会给我一些对齐问题。如果它有多个,布局很好。找到下面的截图,以获得清晰的想法。有人能帮我吗? TIA

用户数据示例-users = [     {accountId:1,姓名:" xyz",电子邮件:" xyz@xyz.com" ;,角色:["超级","常规&#34 ]},     {accountId:2,name:" single role as string",email:" xyz@xyz.com" ;, role:" Super"}];

enter image description here

这是我的代码

   <table class="table table-inverse">
    <thead>
     <th>User Id</th>
     <th>Name</th>
     <th>Email</th>
     <th>Role</th>
    </thead>
    </table>  
   <table class="table table-inverse">
        <tbody>
  <tr ng-repeat="user in users ">
            <td width="10%"><span>{{user.accountId}}</span></td>
            <td width="12%" ><span>{{user.name}}</span></td>
            <td width="14%"><span>{{user.email}}</span></td>
            <td width="12%"><span ng-repeat="role in user.role ">
                {{role}}
            </span></td>
   </tr>
   </tbody>
   </table>   

1 个答案:

答案 0 :(得分:0)

如果没有看到您的数据,我无法确定,但看起来这些用户的角色是字符串而不是像这样的数组。

{accountId: 2, name: "single role as string", email: "xyz@xyz.com", role: "Super"}

在字符串上使用此ng-repeat <span ng-repeat="role in user.role ">}}</span>时,会为每个字母创建一个<span>,这就是为什么它的间距是这样的。

我建议将其更改为一系列角色。

var app = angular.module("app", []);

app.controller("controller", function($scope) {

  $scope.users = [
    {accountId: 1, name: "multiple roles as array", email: "xyz@xyz.com", role: ["Super","Regular"]},
    {accountId: 2, name: "single role as string", email: "xyz@xyz.com", role: "Super"},
    {accountId: 3, name: "single role as array", email: "xyz@xyz.com", role: ["Super"]},
  ];
  
  // Change user roles to arrays if string
  angular.forEach($scope.users, function(user) {
    if (typeof user.role === "string") {
      user.role = [user.role];
    }
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="controller">
  <table class="table table-inverse">
    <thead>
      <th>User Id</th>
      <th>Name</th>
      <th>Email</th>
      <th>Role</th>
    </thead>
  </table>
  <table class="table table-inverse">
    <tbody>
      <tr ng-repeat="user in users ">
        <td width="10%"><span>{{user.accountId}}</span></td>
        <td width="12%"><span>{{user.name}}</span></td>
        <td width="14%"><span>{{user.email}}</span></td>
        <td width="12%"><span ng-repeat="role in user.role ">
                {{role}}
            </span></td>
      </tr>
    </tbody>
  </table>
</div>