Jake Cross Jake Cross - 1 year ago 74
AngularJS Question

Angular binding two scope variables (unwanted action)

I'm trying to have two separate variables (data.newPictures, profile.pictures) which data.newPictures gets it's initial value from after an API call. This happens perfectly, but then once I run the function removeNewPicture($index) they acted like they're binded. So running the function removes both from data.newPictures and profile.pictures. The desired result is the function only removes from data.newPictures, keeping profile.pictures the same.

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,
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);
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),