How to reset scope data to initials value (angular.copy) (Mini-challenge 3) Answer

Table of Content

Check out Mini-challenge 3 Instructions

Answer:

angular.copy challengeIn JavaScript when you copy a variable to another variable, like in the code below, the contain of the variable is get passed by reference and not by value, so when you update the origin variable, the destination variable gets updated too and vice versa:

var var1 = ['value1','value2','value3'];
var var2 = var1;

var2[1] = 'different value';

console.log(var1);
console.log(var2);

/*//result
var1: ["value1", "different value", "value3"]
var2: ["value1", "different value", "value3"]
*/

If you run the code above you will notice the value gets updated in both variables, this happened because JavaScript copy the data by reference not by value. The "Angular way" to solve this problem is with the copy method of the angular object: angula.copy().

var var1 = ['value1','value2','value3'];
var var2 = var1;
var var2 = angular.copy(var2);

var2[1] = 'different value';

console.log(var1);
console.log(var2);

/*//result
var1: ["value1", "value2", "value3"]
var2: ["value1", "different value", "value3"]
*/

 

There are few techniques to achieve this with JavaScript, check out this link:
http://stackoverflow.com/questions/728360/most-elegant-way-to-clone-a-javascript-object

 

This is a jsfiddle code to illustrate this method:

You can find more information here:

If you have a solution for this challenge, different from the proposal solution on this post, don't be shy and share it with us. 🙂