0

I have the following issue:

Let's assume I have a list of posts I will show using ng-repeat. After each post (plain text) I want to show a textbox and button. You can enter a comment in the textbox and when pressing the button you will add a comment to that specific post.

Like in here:

enter image description here

The problem I face is how can I build the model to the $scope in order to be unique for each specific post?

Now I have:

$scope.NewComment ={
    PostId: '',
    Comment: ''
};

If I bind the NewComment.Comment to the textarea then it will not work .. as each of the text-box will actually work for one single post.

Somehow I have to generate dynamic models for each of the post and comment which doesn't sound like a good option.

1
  • 1
    This sounds like a perfect candidate for a directive with an isolate scope :-) Commented Nov 12, 2014 at 19:02

2 Answers 2

1

This problem can be solved by using an angular directive with an isolate scope. This provides a separate scope for each instance of the directive that is created.

The usage of the directive looks like this:

<comment-box ng-repeat="box in boxes" title="box.title" comment="box.comment">

The directive JavaScript:

app.directive('commentBox', function() {
  return {
    restrict: 'E',
    templateUrl: 'CommentBox.html',
    scope: {
      title: '=',
      comment: '='
    }
  }
});

The template html:

<div>
  <h3>{{title}}</h3>
  <input type="text" data-ng-model="comment"/>
  <button data-ng-click="displayComment()">Post</button>
</div>

Here is a working example: http://plnkr.co/edit/4Nw5jpJwH2q3kaIdwNYN?p=preview

You can pass through whatever you want into the isolate scope (including post id, etc.) but this should be a good starting point.

Hope this helps :-)

Sign up to request clarification or add additional context in comments.

Comments

1

You could pass through the specific comment in your post() function, something like this (in sudo-jade syntax...) may work, but I'm not sure if I understand what you are going for.

div(ng-repeat = "post in post")
   {{post.title}}
   input(type="text", ng-model="post.commentText")
   button(ng-click = "postComment(post)")

and in the controller:

$scope.postComment = function (post) {
   console.log(post)
   newComment = {post_id:post.id, test:post.commentText}
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.