Dean Dean - 5 months ago 15
AngularJS Question

Angularjs : Default value setting inside controller

I have a question regarding the angularjs set value and reset it to default.

Here an example

$scope.defaultValue = {
a: 1,
b: 2
}
var dupValue = $scope.defaultValue;

...

function changeValue() {
dupValue.b = 3;
}

...


After I execute the function
changeValue()
, I wish to change my
dupValue
back to
defaultValue
which I simply just call

dupValue = $scope.defaultValue;


Some how it did't work. Because the
defaultValue
's element has changed due to the function i executed.

Is there any method to make this work?

Answer

You'are not copying the defaultValue, but just assigning the reference to it. Therefore when you modify dupValue you also make change to defautValue.

Assign default value using:

dupValue = angular.copy($scope.defaultValue);

See this fiddle