2014-09-28 71 views
0

這可能是非常基本的,但我會圍繞圈子。我如何定位一個嵌套重複實例?

我有一個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; 
      }); 

    }); 

    }); 

會發生什麼,在這個例子是,評論控制器的所有實例將使用相同的意見進行填充 - 我只是需要能夠針對相關的一個。我確信我錯過了一些非常基本的東西,並可能以這種錯誤的方式進行。

非常感謝。

+0

可以請設置一個plunker,它會很容易使用plunker – harishr 2014-09-28 12:11:30

+0

爲什麼解決問題'PostsCtrl'中的'showComments()'方法,而不是'它屬於'CommentsCtrl'中?將解決問題,並且不需要任何事件。否則,您可以簡單地檢查廣播的帖子ID是否與CommentsCtrl範圍內的帖子的ID相同。 – 2014-09-28 12:39:43

回答

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> 

將帖子Ctrl轉移到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; 
    }; 
    }); 
+0

太棒了,現在都在工作 - 感謝Tim的幫助。 – 2014-09-28 15:00:56