如何使用ng repeat使用键渲染嵌套的json对象

时间:2017-08-08 12:08:03

标签: javascript angularjs

我正在尝试搜索解决方案,但没有得到它。我还使用嵌套ng重复和使用ng repeat的不同方法,Items值总是以字符串形式出现。

我想这样显示,

   _id: 59889d877560a92480a4b354
   firstName: ayaz
   lastName: khatri
   items: 
         _id:item3,
         _name:My Item #4
         _price:999.99
         _quantity:1

   totalItems: 1
   totalPrice: 999.99

这里是控制器

    var app = angular.module('app', []);
    app.controller('mainCtrl', function($scope) {
    $scope.userInfo = {
    "_id" : ObjectId("59885d800560a92480a4b354"),
    "firstName" : "ayaz",
    "lastName" : "khatri",
    "items" : [ 
       {
             "_id" : "item3",
             "_name" : "My Item #4",
             "_price" : 999.99,
             "_quantity" : 1
       }
              ],
    "totalItems" : 1,
    "totalPrice" : 999.99
    }

  });

这里是ng视图

  <body ng-controller="mainCtrl" class="container" style="padding-top:30px">
   <ul ng-repeat="user in userInfo">
     <li ng-repeat="(x,y) in user">

      {{x}}:{{y}}

     </li>

   </ul>
  </body>
  </html>

1 个答案:

答案 0 :(得分:0)

我分叉你的plunkr示例它有效here

您可以通过创建自定义角度is_object方法并执行如下操作来确定嵌套值是否为对象。

// javascript

$scope.is_object = function (something) {
    return typeof (something) == 'object' ? true : false;
};

// html(列表解决方案)

<ul ng-repeat="user in userInfo">
  <li ng-repeat="(x,y) in user">
    {{x}} :
    <span ng-if="is_object(y) == false"> {{ y }} </span>
    <ul ng-if="is_object(y)">
      <li ng-repeat="(k,v) in y">
          <br>
          <ul>
            <li ng-repeat="(k2,v2) in v">
               {{k2}} : {{ v2 }}
            </li>
          </ul>
      </li>
    </ul>
  </li>
</ul>

// html(表格解决方案)

<table ng-repeat="user in userInfo" border="1">
  <tr ng-repeat="(x,y) in user">
    <td>
        {{x}} :</td>
        <td>
        <span ng-if="is_object(y) == false"> {{ y }} </span>
        <ul  ng-if="is_object(y)" style="list-style:none; margin-left:-60px">
          <li class="border-right: 1px solid" ng-repeat="(k,v) in y" style="float:left;border-right: 1px solid" >
              <br>
              <ul>
                <li ng-repeat="(k2,v2) in v">
                   {{k2}} : {{ v2 }}
                </li>
              </ul>
          </li>
        </ul>
    </td>
  </tr>
</table>