Cancel changes AngularJS

0

I have the following code to undo the changes:

    $pageContent = content;
    $scope.page = $pageContent.page;
    var pageBackup = $pageContent.page;

    $scope.cancelChanges = function() {
        $scope.page = pageBackup;
        $scope.$apply;
    };

But when I change something in $scope.page it also changes pageBackup . Could someone explain the reason for this?

    
asked by anonymous 23.04.2014 / 23:19

1 answer

5

You are just creating a new reference for the object, so any change in the original reflects in the reference.

The output is copy the original object, and recover the backup of this copy.

$pageContent = content;
$scope.page = $pageContent.page;

$scope.backup = {};
angular.copy( $scope.page, $scope.backup );
// Ou, se preferir:
// $scope.backup = angular.copy( $scope.page );

$scope.cancelChanges = function() {
    angular.copy( $scope.backup, $scope.page );
    $scope.$apply;
};
    
23.04.2014 / 23:29