AngularJS - angular.copy

The initial setup:

<body ng-app="app" ng-controller="AppCtrl as app">

  <form>
    <input type="text" ng-model="app.selectedContact.firstName" />
    <buttin ng-click="app.saveContact()">Save</button>
  </form>

  <div class="div" style="margin-top: 40px;"></div>

  <table class="table table-striped">
    <thead>
      <tr>
        <td>First</td>
        <td>Last</td>
        <td>Phone</td>
      </tr>
    </thead>
    <tbody>
      <tr ng-repeat="contact in app.contacts" ng-click="app.selectedContact(contact)">
        <td>{{contact.firstName}}</td>
        <td>{{contact.lastName}}</td>
        <td>{{contact.phone}}</td>
      </tr>
    </tbody>
  </table>

</body>
var app = angular.module("app", ["ngAnimate"]);

app.factory("contacts", function () {
  return [
    {"firstName": "Angelica", "lastName": "Britt", "phone": "513-0955"},
    …
  ];
});

app.controller("AppCtrl", function (contacts) {
  this.contacts = contacts;
  this.selectedContact = null;

  this.selectedContact = function (contact) {
    this.selectedContact = contact;
  }
});

Our desired functionality is to have a click edit a row entry, create a temporary copy of the row data, then update.

  <form>
    <input type="text" ng-model="app.contactCopy.firstName" />
    <buttin ng-click="app.saveContact()">Save</button>
  </form>
app.controller("AppCtrl", function (contacts) {
  this.contacts = contacts;
  this.selectedContact = null;
  this.contactCopy = null;

  this.selectedContact = function (contact) {
    this.selectedContact = contact;
    this.contactCopy = angular.copy(contact);
  }
});

This adds the middle contactCopy attribute which uses the helper method angular.copy() to make a deep copy of the contact object. With this, we now see the table does not update when the input changes. To make the save button work:

app.controller("AppCtrl", function (contacts) {
  this.contacts = contacts;
  this.selectedContact = null;
  this.contactCopy = null;

  this.selectedContact = function (contact) {
    this.selectedContact = contact;
    this.contactCopy = angular.copy(contact);
  }

  this.saveContact = function () {
    this.selectedContact = this.contactCopy;
});

This doesn’t appear to work. The reason for this is that selectedContact is being overwritten, so we instead need to assign the firstName attribute instead:

app.controller("AppCtrl", function (contacts) {
  this.contacts = contacts;
  this.selectedContact = null;
  this.contactCopy = null;

  this.selectedContact = function (contact) {
    this.selectedContact = contact;
    this.contactCopy = angular.copy(contact);
  }

  this.saveContact = function () {
    this.selectedContact.firstName = this.contactCopy.firstName;
});

Now, you can see the save function works properly.