0

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 = {};
});

3 Answers 3

3

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

newPictures: angular.copy($scope.profile.pictures),
Sign up to request clarification or add additional context in comments.

1 Comment

Used this, seems more "Angular" I guess haha. Thanks :)
1

They are basically the same object.

You should assign newPictures like $scope.profile.pictures.slice(0); in order to get the array copied.

Snippet would become:

$scope.data = {
            edit: false,
            newPictures: $scope.profile.pictures.slice(0),
            newBiography: $scope.profile.biography,
            newFeatures: $scope.profile.features,
            newStarting_fees: $scope.profile.starting_fees
        };

Comments

1

$scope.data.newPictures and $scope.profile.pictures refer the same object.
You should 'clone' the object you want to copy:

...
newPictures: jQuery.extend(true, {}, $scope.profile.pictures);
...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.