Skip to content Skip to sidebar Skip to footer

Editing An Item From Ng-repeat

So far I've been successful in creating a function that removes an element from ng-repeat and to toggle a form. I can't figure out how to edit a given element in that ng-repeat. Id

Solution 1:

You need to tell which item you want to edit. So it should be

<span ng-click="vm.edit(item)">E</span>

Then this function should store a copy of that item to edit in some variable:

vm.edit= function(item) {
  vm.editedItem = angular.copy(item);
};

And the form should be bound to this item copy:

<input type="text" ng-model="vm.editedItem.name"/>
<input type="text" ng-model="vm.editedItem.desc"/>

Then the save method should find back the original item in the array (thanks to its ID or index), and copy the edited fields from vm.editedItem.


Solution 2:

angular
  .module('testApp', [])
  .controller('testCtrl', testCtrl)
  .service('testSrvc', testSrvc);

function testCtrl(testSrvc) {
  var vm = this;
  vm.list = testSrvc.list;
  this.index1 = -1;
  vm.removeItem = function(idx) {
    testSrvc.remove(idx);
  }

  vm.showEditForm = false;
  vm.toggleEditForm = function(item,index) {
     this.show = true;
     this.index1 = index;
  };

  vm.update = function(item,index) {
    vm.list[index].name = item.name;
     vm.list[index].desc = item.desc;
    this.index1 = -1;
  }
}

function testSrvc() {
  this.show = false;
  this.list = [
    {
      name: 'asdf',
      desc: 'lorem ipsum dolor'
    },
    {
      name: 'qwerty',
      desc: 'lorem ipsum amet'
    }
  ];

  this.remove = function(itemIndex) {
    this.list.splice(itemIndex, 1);
  };

  this.edit = function(index) {
    this.show = true;
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="testApp">
  <div ng-controller="testCtrl as vm">
    <form ng-show="vm.showEditForm">
      
    </form>
    <table>
      <tr>
        <th>Name</th>
        <th>Description</th>
      </tr>
      <tr ng-repeat="item in vm.list" >
        <td>
          {{item.name}}
        </td>
        <td>
          {{item.desc}}
          <span ng-click="vm.toggleEditForm(item,$index)">E</span>
          <input ng-show="vm.index1 == $index" type="text" ng-model="item.name"  />
          <input ng-show="vm.index1 == $index" type="text" ng-model="item.desc" />
            <button ng-show="vm.index1 == $index" ng-click="vm.update(item,$index)">Submit</button>
          <span ng-click="vm.removeItem($index)">X</span>
        </td>
      </tr>
    </table>
  </div>
</div>

Post a Comment for "Editing An Item From Ng-repeat"