Sajeev C Sajeev C - 4 months ago 29
AngularJS Question

angularjs- data binding issue in textareas

I have built a timeline using angular js. Timeline shows post from users and other people can add comment for it. For that, I have provided a textarea.
Setup is simple. i use ng-repeat to show timeline post (which can always be more than one) and as users can comment on each post, textarea is included along with it (like facebook timeline)

So, when I ng-repeat the content, textarea also gets repeated. That is exactly what I need.

But, data-binding is done. So when I type on a textarea, all textarea reflects it. It's like type on one comment textarea, all text-area will show being typed.

How can I avoid that? I'm new to angularJS

This is my sample code:

<li class="media post" ng-repeat="post in vm.posts">
<div class="post-main">
this is a static post
</div>

<div class="media comment-textarea">

<div class="media-body">
<textarea class="form-control" placeholder="Type here..." rows="1" ng-model="vm.comment.content"></textarea>
<a class="btn btn-primary " ng-click="vm.addComment(post,vm.currentComment.content)">
<i class="fa fa-paper-plane"></i>
</a>
</div>
</div>
</div>
</li>

Answer

Because you are using same model value for all timelines, instead I'd suggest you to put comment model inside post object only. Make sure you have added comment property to each post record.

<li class="media post" ng-repeat="post in vm.posts">
    <div class="post-main">
      this is a static post
    </div>

        <div class="media comment-textarea">

            <div class="media-body">
                <textarea class="form-control" placeholder="Type here..." rows="1" 
                   ng-model="post.comment.content"></textarea>
                <a class="btn btn-primary " ng-click="vm.addComment(post,post.comment.content)">
                    <i class="fa fa-paper-plane"></i>
                </a>    
            </div>
        </div>
    </div>
</li>