jack_snipe
jack_snipe

Reputation: 129

AngularJS ng-repeat input

I am trying to make comments functionality using Angular js. The problem is that when i want to write a comment for a post, the text is also writing inside other input elements (comments). I write a text inside one input, but it writes it in all inputs

So for example same is happening with this code

<div class="comments" ng-repeat="articles in [1,2,[4,5,6]]">
<div ng-repeat="comments in articles">
    <div>
        <input type="text" ng-model="$parent.new">
    </div>
</div>

if i use new instead of $parent.new i get undefined, but when i use $parent.new and i write in one input, it also writes in other inputs.enter image description here

Upvotes: 3

Views: 5832

Answers (3)

NTP
NTP

Reputation: 4448

Change ng-model of input to

<input type="text" ng-model="comments.comment">

Upvotes: 0

Christian Santos
Christian Santos

Reputation: 5456

The issue is that you are assigning all of the inputs to the same model, so your inputs are all in sync with the same object.

What you need is to assign each input to a different model. I'm guessing you need these models to be dynamic, so you should use an array as your model and track your ng-repeat by $index like so:

<div ng-repeat="comments in articles track by $index">
    <div>
        <input type="text" ng-model="arr[$index]">
        <span ng-if="arr[$index]">
            {{arr[$index]}}
        </span>
    </div>
</div>

Now, in your controller, you can initialize the empty arr like so:

$scope.arr = [];

Now, your inputs will be in sync with $scope.arr depending on the index they were in.

Try out this jsfiddle for an example.

Upvotes: 3

Muhammad Usman
Muhammad Usman

Reputation: 10148

This is because you've giving same model (ng-model="$parent.new") for all of the inputs What you should do to avoid this problem is assign different model to each input element. Something like

<div class="comments" ng-repeat="articles in [1,2,[4,5,6]]">
<div ng-repeat="comments in articles">
<div>
    <input type="text" ng-model="comments">
</div>
</div>

Upvotes: 0

Related Questions