angular.copy

John Lindquist
InstructorJohn Lindquist
Share this video with your friends

Social Share Links

Send Tweet

In this episode John takes a look at angular.copy and how you can use it for non-destructive form editing. Instead of binding to a value directly, we make a deep copy of that object and bind to the copy for presentation. Updates to the data are then "saved" to the original object to persist changes.

John Lindquist: A fairly common scenario in Angular is to just loop through a list of data. When you click on one of the list, you want to edit that value and type something new. But usually you don't want to update just what's in like a row. Instead of updating this, let's look at a way to make a temporary copy and then update. Right now I have my model bound to the selectedContact.

What I'm actually going to do is change this to a contact copy. Then when I select my contact, I will say this selected or contactCopy is angular.copy. This angular.copy method is a helper function, which allows you to make a deep copy of whatever you use here. I'm going to make a deep copy of the contact. I'm still going to store the selectedContact here so that I can update it later.

If I make this deep copy, and just as a good practice we'll have a contactCopy here, as well. If I make this deep copy, I can actually click now and get the value. Nothing changes, just like we want. Let's implement what happens when we save. When I click on save, I have app.saveContact. Let's say this.saveContact. Then we're going to take the value of the contactCopy and then assign it to the selectedContact.

This is going to break on purpose, just to show you why. contactCopy. You'll see when we do this. I hit save, nothing happens. That's because we're actually overriding what selectedContact. We're reassigning it to something else. Or what we actually want to do is just update one of the properties on this. In this scenario, we're updating the first name. If I come in here, click Angela. Delete a few characters and hit save. You'll see that Angela changed to Angel. Or was it, Angelica changed to Angel. If I click Amery, I can save. Click on Wendy and make it William.

You can see the process here is a simple table, just looping through the app.contacts. When I click on one, it's going to select it and pass in the current contact. When I update my input here, I bind it to the contactCopy, not the selectedContact, so that the copy of the contact can be updated. When I'm done with that copy, I'm going to take the property off of the copy and assign to the property on the selectedContact object.