Cancel changes to Angularjs

Asked

Viewed 111 times

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 into $scope.page also changes in the pageBackup. Could someone explain to me why this occurs?

1 answer

5


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

The exit 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;
};
  • I managed to take the angular.copy same XD was worth

Browser other questions tagged

You are not signed in. Login or sign up in order to post.