Growler Growler - 4 months ago 9
AngularJS Question

ng-repeat with inline text editing affects other items

Using Angular (

"angular": "~1.4.3"
), I have a ng-repeated list which I'd like to add items to and edit the item name inline using a text box.

enter image description here

The problems occur when I add more than one new item to the array. When I change the text in one, it affects the other. I typed
Hello
for line item 1, and it pushed
H
onto line item 2, and the rest on 1:

enter image description here

This is how I'm adding new objects (using
unshift
to force it to top of list):

$scope.addObj = function () {
$scope.new_categories.unshift({
category : '',
other data...
});
};


HTML:

<tr ng-repeat="c in new_categories | orderBy:sortType:sortReverse | filter:searchCategories track by $index" class="newly-added">
<td class="third-width-input">
<input type="text" name="category" placeholder="New Category" class="form-control" ng-blur="" ng-model="c.category">
</td>
</tr>

Answer

You're using the same ngModel for all of your inputs. You should change it to:

<input type="text" ng-model="c.category[$index]" name="category" placeholder="New Category" class="form-control" ng-blur="">

So you can have this:

<tr ng-repeat="c in new_categories | orderBy:sortType:sortReverse | filter:searchCategories track by $index" class="newly-added">
    <td class="third-width-input">
        <input type="text" ng-model="c.category[$index]" name="category" placeholder="New Category" class="form-control" ng-blur="">
    </td>
</tr>
Comments