使用ng-repeat显示来自所有对象的嵌套数据

时间:2017-09-11 20:11:35

标签: angularjs

嘿,我有许多产品的数据库,每个产品都有评论,并会使用ng-repeat显示每条评论。 data.data.products数据库中有所有对象,comments对每个对象都有注释。例如我在数据库中有五个对象,每个都有六个注释。我的问题是所有对象的显示有多么不同? 我尝试使用这样的东西:

User.getProducts().then(function(data){
   for(i=0; i < data.data.products.length; i++)
   app.UserComments = data.data.products[i].comments;   
})

HTML

<div ng-repeat="comment in main.UserComments" class="item"> 
  <blockquote>
     <p>{{comment.body}}</p>
  </blockquote> 
</div> 

模式

var productSchema = new Schema({
comments: [{
    body: {
        type: String,
        trim: true,
    },
    author: {
        type: String,
    },
    date: {
        type: Date,
    }
}]
});

1 个答案:

答案 0 :(得分:0)

只需将您的Web服务返回的数据分配给控制器变量,然后使用“controller as”语法,在ng-repeat的视图中对它们进行迭代。

<html ng-app="sampleApp">
<head>
  <meta charset="utf-8" />
  <title>Sample App</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js"></script>
  <script>
    var myapp = angular.module('sampleApp', []);

    myapp.controller('SampleController', function() {

      this.data = [
        { product: 'A great product', comments: 'A sample comment' },
        { product: 'Another great product', comments: 'Another sample comment' }
      ];

    }); 

  </script>
</head>
<body ng-controller="SampleController as sampleCtrl">

  <div ng-repeat="item in sampleCtrl.data">
    <blockquote>
      <p>{{item.comments}}</p>
    </blockquote>
  </div>

</body>
</html>