Erma Isabel Erma Isabel - 18 days ago 5
AngularJS Question

AngularJS Updating Variable

I have a global variable and I am assigning a JSON to the global variable on click. However, even when I am not clicking, the global variable is also getting updated.

$scope.save = function() { // method called on click
DataBasket.users = $scope.usersPermissions; // Actually DataBasket is a factory, updating global variable
}


I am also manipulating the value of
$scope.usersPermissions
on other clicks. But I don't want it to be updated to the global variable.

How can I solve this?

Answer

I think that what you want is DataBasket.users to be a copy of $scope.usersPermissions. Try doing this:

$scope.save = function() {
    DataBasket.users = angular.copy($scope.usersPermissions);
}

Otherwise DataBasket.users will reference the same object as $scope.usersPermissions and whenenever you change one, the other will change too, because actually they will be the same object.