這可能是非常基本的,但我會圍繞圈子。我如何定位一個嵌套重複實例?
我有一個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;
});
});
});
會發生什麼,在這個例子是,評論控制器的所有實例將使用相同的意見進行填充 - 我只是需要能夠針對相關的一個。我確信我錯過了一些非常基本的東西,並可能以這種錯誤的方式進行。
非常感謝。
可以請設置一個plunker,它會很容易使用plunker – harishr 2014-09-28 12:11:30
爲什麼解決問題'PostsCtrl'中的'showComments()'方法,而不是'它屬於'CommentsCtrl'中?將解決問題,並且不需要任何事件。否則,您可以簡單地檢查廣播的帖子ID是否與CommentsCtrl範圍內的帖子的ID相同。 – 2014-09-28 12:39:43