Jake Cross Jake Cross - 1 year ago 81
AngularJS Question

Deep copy (unbind) two scope variables - AngularJS

I'm trying to have two separate variables (

), one initialized with the values of the other.

Initialization runs well, but when I edit one runnig function
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
, keeping profile.pictures unchanged.

Any ideas how to prevent this?

app.controller('ModelController', function($scope, $rootScope, $state, $stateParams, $models, $toast) {
.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) => {
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 Source

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

newPictures: angular.copy($scope.profile.pictures),
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download