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

<spanng-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:

<inputtype="text" ng-model="vm.editedItem.name"/>
<inputtype="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);

functiontestCtrl(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;
  }
}

functiontestSrvc() {
  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;
  }
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script><divng-app="testApp"><divng-controller="testCtrl as vm"><formng-show="vm.showEditForm"></form><table><tr><th>Name</th><th>Description</th></tr><trng-repeat="item in vm.list" ><td>
          {{item.name}}
        </td><td>
          {{item.desc}}
          <spanng-click="vm.toggleEditForm(item,$index)">E</span><inputng-show="vm.index1 == $index"type="text"ng-model="item.name"  /><inputng-show="vm.index1 == $index"type="text"ng-model="item.desc" /><buttonng-show="vm.index1 == $index"ng-click="vm.update(item,$index)">Submit</button><spanng-click="vm.removeItem($index)">X</span></td></tr></table></div></div>

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