torresito
torresito

Reputation: 67

Angular: how to save edited values?

here is my plnkr http://plnkr.co/edit/0W1SZll1BOK5uuEtdycy?p=preview

im trying to save edited values from my edit contact modal.

here is a edit method that takes current value from object:

$scope.edit = function(terminal) {
$scope.name = terminal.name;
$scope.last = terminal.last;
$scope.age = terminal.age;
}

i read about angular copy, there is anything else? any one can help me please ill glat to learn how to do that

Upvotes: 0

Views: 2239

Answers (3)

charlietfl
charlietfl

Reputation: 171690

You are creating a lot of extra manual work by not using one object in ng-model in the first place instead of using individual scope properties.

There is a golden rule also that if you don't have a dot in ng-model you are doing it wrong

Do something like:

<input ng-model="terminal.name">
<input ng-model="terminal.age">

Then work along the following lines:

$scope.edit = function(terminal) {
    // store reference to terminal being edited
    $scope.currentTerminal = terminal;
    // make a copy so live one is not affected -- will be used in form
    $scope.terminal = angular.copy(terminal);
}

$scope.save = function(){
  // update stored original with changes
  angular.extend($scope.currentTerminal,  $scope.terminal);
  // reset terminal used in form
  $scope.terminal ={};
}

I would strongly suggest you get rid of jQuery and bootstrap.js and use angular-ui-bootstrap insted

Upvotes: 1

Ajay Singh
Ajay Singh

Reputation: 1281

You need to pass the index of the row that you are going to edit. pass the index when you click on edit button.

Change in script.js

$scope.edit = function(terminal,index) {

    $scope.name = terminal.name;
    $scope.last = terminal.last;
    $scope.age = terminal.age;
    $scope.edit_index = index

 }


$scope.saveEdit =function(){
    index = $scope.edit_index
    $scope.terminals[index].name = $scope.name;

  }

Change in index.html

<td> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#editModalLong" ng-click="edit(terminal,$index)">Edit</button>

<button type="button" class="btn btn-primary" data-dismiss="modal" ng-click="saveEdit()">Save</button>

http://plnkr.co/edit/GpVB2dUiHCY6NslQDuBe?p=preview

Upvotes: 1

haMzox
haMzox

Reputation: 2109

Use angular.copy when assigning value of object or array to another variable and that object value should not be changed.

Without deep copy or using angular.copy, changing value of property or adding any new property update all object referencing that same object. Your JS will look like this:

$scope.edit = function(terminal) {
    $scope.name = angular.copy(terminal.name);
    $scope.last = angular.copy(terminal.last);
    $scope.age = angular.copy(terminal.age);
    }

Upvotes: 2

Related Questions