Dileep Dileep - 1 year ago 75
AngularJS Question

How to update ng-repeat values in angular js?

I am new to angularjs,I have an array I am looping it through

directive,and I have written code for copy,remove,and edit values in the array.if I want to remove or copy I can do it,but if I click on edit one popup box will appear there I want to edit the values those updated values should update in the array.how can I get it done ?

<!doctype html>
<title>Angular app</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.17/angular.min.js">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<style type="text/css">
margin-bottom: 30px;
width: 250px;
height: 250px;
border: 1px solid black;
display: none;
position: absolute;
top: 0px;
left: 0px;
bottom: 0px;
right: 0px;

display: block;
display: none;
<body ng-app="myApp">
<div ng-controller="myCon">
<div ng-repeat="s in items" class="listv">
<button ng-click="removeStudent($index)">remove</button>
<button ng-click="copyrow($index)">copy</button>
<button ng-click="editrow($index)">edit</button>

<div class="editpopup editpopup-{{istrue}} ">
<p>edit id:<input type="text" ng-model="editedid"></p>
<p>edit pname:<input type="text" ng-model="editedname"></p>
<button ng-click="save($index)">save</button>
<button ng-click="closepopup()">cancel</button>


var myApp=angular.module('myApp',[]);
$scope.items=[{id:1,pname:'box1'},{id:2,pname:'box2'}, {id:3,pname:'box3'}];





here is jsfiddle

Answer Source

The easiest way is to use angular.copy to create a clone of the object when edit is clicked and then when save is clicked copy the data to the item in the array.

First initilize $scope.editedItem

$scope.editedItem = {};

For editrow we store the currently edited index in $index and then clone the data into $scope.editedItem.

    $scope.$index = $index;
    angular.copy($scope.items[$index], $scope.editedItem);

Then in save we clone the data back into the object in the array:

    angular.copy($scope.editedItem, $scope.items[$scope.$index]) 

The view needs to be updated to instead use editedItem:

<div class="editpopup editpopup-{{istrue}} ">
    <p>edit id:<input type="text" ng-model="editedItem.id"></p>
    <p>edit pname:<input type="text" ng-model="editedItem.pname"></p>
    <button ng-click="save()">save</button>
    <button ng-click="closepopup()">cancel</button>


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download