如何仅针对嵌套重复的一个实例?

时间:2014-09-28 12:05:22

标签: angularjs angularjs-scope angularjs-ng-repeat

这可能是非常基本的,但我会围成一圈。

我在ng-repeat中有一个嵌套控制器 - 我想在重复实例中触发一个事件,它只影响该实例中的嵌套控制器,而不是所有实例中的嵌套控制器。

这是尝试使事情更清晰的基本示例:

<div ng-controller="PostsCtrl">
  <div ng-repeat="post in posts">
    <p>{{post.body}}</p>
    <div ng-controller="CommentsCtrl">
      <div ng-repeat="comment in comments">
        <p>{{comments.body}}</p>
        <a href ng-click="showComments(post.id)">Show comments</a>
      </div
    </div>
  </div>
</div>


angular.module('myApp')
  .controller('PostsCtrl', function ($scope, Restangular) {

        var posts = Restangular.all('posts');

        posts.getList().then(function(posts) {
            $scope.posts = posts;
        });

        $scope.showComments = function(id) {
            $scope.$broadcast('SHOW_COMMENTS', id);
        };

  });


angular.module('myApp')
  .controller('CommentsCtrl', function ($scope, Restangular) {

    $scope.$on('SHOW_COMMENTS', function(event, id) {

            var post = Restangular.one('posts', id);

            post.get().then(function(post) {
              $scope.comments = post.comments;
            });

    });

  });

在这个例子中会发生的是注释控制器的所有实例都会填充相同的注释 - 我只需要能够定位相关的注释。我确定我错过了一些非常基本的东西,并且可能以错误的方式解决这个问题。

非常感谢。

1 个答案:

答案 0 :(得分:0)

您正在向所有重复的帖子广播“SHOW_COMMENTS”。您需要隔离每个帖子的范围。

使用ng-controller =“PostCtrl”隔离范围。

<div ng-controller="PostsCtrl">
  <div ng-repeat="post in posts" ng-controller="PostCtrl">
    <p>{{post.body}}</p>
    <div ng-controller="CommentsCtrl">
      <div ng-repeat="comment in comments">
        <p>{{comments.body}}</p>
        <a href ng-click="showComments()">Show comments</a>
      </div
    </div>
  </div>
</div>

将显示评论从PostsCtrl移动到PostCtrl。

angular.module('myApp')
  .controller('PostCtrl', function ($scope) {
     $scope.showComments = function() {
        $scope.$broadcast('SHOW_COMMENTS', $scope.post.id);
    };
  });

你真的需要使用活动吗?您可以使用ng-if。

您的评论无论如何都嵌入在每个帖子中,所以为什么要再次请求它们。在这种情况下,你可以做这样的事情......

<div ng-controller="PostsCtrl">
  <div ng-repeat="post in posts" ng-controller="PostCtrl">
    <p>{{post.body}}</p>
    <a href ng-click="toggleComments()">Show comments</a>
    <div ng-controller="CommentsCtrl" ng-if="showComments">
      <div ng-repeat="comment in post.comments">
        <p>{{comments.body}}</p>
      </div
    </div>
  </div>
</div>

切换评论......

angular.module('myApp')
  .controller('PostCtrl', function ($scope) {
     $scope.showComments = false;

     $scope.toggleComments = function() {
        $scope.showComments = !$scope.showComments;
     };
  });