user3871
user3871

Reputation: 12718

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>

EDIT: Be advised, using $index suggested in the answer will change the structure of your object.

PLUNKER

Binding the model as I originally have, c.category_name maintains:

{
   //This is a Category Object
    category_name: 'some string',
    other data on the category obj
}

But using c.category_name[$index] changes it:

{
   //This is a Category Object
   category_name: Object { 0 : 'some string' },
   other data on the category obj
}

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[$index]">
    </td>
    <button ng-class="{ 'button-error' : !c.category[$index].length }" type="button" ng-click="saveAddedCategory( c ); c.saving = true; c.updated = false" class="buttons green inline" ng-disabled="!c.category[$index].length">
        Save
    </button>
</tr>

JS:

    $scope.saveAddedCategory = function(category) {
        console.log('cat', category);
    };

Console.log produces:

enter image description here

Upvotes: 1

Views: 518

Answers (1)

developer033
developer033

Reputation: 24884

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>

Upvotes: 3

Related Questions