Answer the question
In order to leave comments, you need to log in
How to get post.id elsewhere in angularjs code with ng-repeat?
<div data-ng-repeat="post in posts>
<div>{{post.id}}</div>
<div>{{post.title}}</div>
<div class="load-comments" data-ng-model="comments" data-ng-click="loadComments(post)">load-comments</div>
</div>
$scope.loadComments = function (post) {
CommentsService.comments({post_id: post.id}).$promise.then(function (data) { //сервис для получения коментов
$scope.comments = data.results; /тут данные в json
});
<div data-ng-repeat="comment in comments" class="ng-scope">
<div class="ng-binding">{{comment.id}}</div>
<div class="ng-binding">{{comment.id}}</div>
</div>
<input type="text" placeholder="Add a comment..." data-ng-model="viewModel.commentText" data-ng-disabled="viewModel.isCommentSending" class="ng-pristine ng-valid">
$scope.addComment = function (post) {
console.log(post);
return CommentsService.createComment({
text: $scope.viewModel.commentText,
post_id: post.id
}).then(function (comment) {
$scope.post.comments.unshift(comment);
$scope.post.comment_count++;
$scope.viewModel.commentText = '';
console.log(123123, comment, $scope.post.comments);
}).finally(function () {
$scope.viewModel.isCommentSending = false;
});
};
Answer the question
In order to leave comments, you need to log in
The simplest and, in my opinion, the correct way - directives. You can isolate everything related to one post inside a directive.
Within this directive, you can already display comments, you have access to the post itself, and so on. The problem with spinners can be solved through services - passing a directive delegate inside another one... or communicating through controllers... there are already a lot of options, as you like.
If you are using angular 1.4 then the directive will look something like this:
function singlePostViewDirective () {
return {
templateUrl: 'post.template.html',
bindToController: {
data: '=post'
},
controller: function () {
var vm = this;
vm.addComment = function (comment) {
// do stuff
}
},
controllerAs: 'post'
}
}
<form ng-submit="post.addComment(commentText)">
<textarea ng-model="commentText"></textarea>
<input type="submit" />
</form>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question