Jake Cross Jake Cross - 5 months ago 36
AngularJS Question

Deep copy (unbind) two scope variables - AngularJS

I'm trying to have two separate variables (

data.newPictures
,
profile.pictures
), one initialized with the values of the other.

Initialization runs well, but when I edit one runnig function
removeNewPicture($index)
I edit also the second one (like they're binded).

The expected result is the total independence of the two objects, so that function only removes data from
data.newPictures
, keeping profile.pictures unchanged.

Any ideas how to prevent this?

app.controller('ModelController', function($scope, $rootScope, $state, $stateParams, $models, $toast) {
$models.getModel($stateParams.uid)
.then((model) => {
$scope.profile = model;

$scope.data = {
edit: false,
newPictures: $scope.profile.pictures, // <<< Initialization
newBiography: $scope.profile.biography,
newFeatures: $scope.profile.features,
newStarting_fees: $scope.profile.starting_fees
};
})
.catch((err) => {
$toast.error(err.err);
if(err.code === 69) $state.go('login');
});

$scope.removeNewPicture = ($index) => {
$scope.data.newPictures.splice($index, 1); // <<< This edits both the objects
console.log($scope.data.newPictures, $scope.profile.pictures);
};

$scope.profile = {};
$scope.data = {};
});

Answer

Picture and newPicture reference the same array. Create a copy to newPictures to avoid this issue

newPictures: angular.copy($scope.profile.pictures),
Comments