【问题标题】:AngularJS ng-repeat with different objectsAngularJS ng-repeat 与不同的对象
【发布时间】:2014-07-14 20:24:06
【问题描述】:

我是 AngularJS 的新手,并且编写了一个调用特定 API 的应用程序。它像这样返回一个对象:

posts = [
    posts = [...]
    users = [...]
]

这就是 HTML 模板:

<div id="{{'post-' + $index}}" ng-repeat="post in posts.posts">
    <article>
       <h1>{{post.user.username}}</h1>
       <span>{{post.date | date: "dd.MM.yy, HH:mm"}}</span>
       <p>{{post.content}}</p>
    </article>
</div>

我想显示不同的帖子(来自帖子对象),包括用户名(在用户对象中)。如何告诉 Angular 帖子在帖子对象中,并且正确的用户名在用户对象中?

【问题讨论】:

  • 帖子是什么样的? postsuser 数组是一对一映射的吗?
  • 在我看来,您返回的数据格式应该更好。现在的方式是您假设存在一对一的关系。如果是这种情况,那么您应该能够将它们都放在同一个对象中。

标签: arrays json angularjs object


【解决方案1】:

ngRepeat 为每个条目创建一个新范围。该范围将包含数组中当前偏移量的$index。由于它是一个新范围,因此变量 posts 现在位于 $parent 范围内。

假设postsusers 包含并行数据并且是数组。您可以使用$indexusers 中查找数据。

<h1>{{$parent.posts.users[$index].username}}</h1>`

【讨论】:

    【解决方案2】:

    没有看到 postsusers 对象的结构,很难准确地说,但总体思路是使用 users 对象,以及来自 post 对象的 user_id,所以要么像这样:

    <h1>{{users[post.user.id].username}}</h1>
    

    或者像这样:

    <h1>{{getUserNameForPost(post)}}</h1>
    
    $scope.getUserNameForPost = function(post) {
         //find the user based of the post however you want
         user = $scope.users.filter(function(u) { return u.id = post.user });
         return user[0].username;
    }
    

    【讨论】:

      【解决方案3】:

      如果可能,我建议您将返回的 JSON 对象的结构更改为类似于以下的结构:

      posts = [
          { 
          id : "post id",
          title: "Post title",
          content: "Post content",
          date : "post date",
          user : {
              id: "user id",
              name: "user name"
              }
          },
          ....
          ....
      ]
      

      这应该可行。

      【讨论】:

        猜你喜欢
        • 2017-09-13
        • 1970-01-01
        • 1970-01-01
        • 2017-03-17
        • 2014-09-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多