Question

The problem is this:

$scope.model1 = [1,2,3,4,5,6,7];
$scope.model2 =  $scope.model1;

$scope.model2.splice(2, 1);

 <pre>{{model1}}</pre>
 <pre>{{model2}}</pre>

Return:

[1,2,4,5,6,7]
[1,2,4,5,6,7]

Need:

 [1,2,3,4,5,6,7]
 [1,2,4,5,6,7]

Why is this happening?

Update: solution: Everywhere use angular.copy($scope.val) My code is bad:

$scope.$watch('checkedImages', function (newVal) {
        if (newVal !== undefined && newVal[0] !== undefined) {
            if ($scope.model.curSupplier === undefined) {
                $scope.model.curSupplier = newVal[0].supplier_id;
                $scope.model.curCheckedImages = newVal;
            }
            $scope.supplier = newVal[0].supplier_id;
        }
    });

vs

$scope.$watch('checkedImages', function (newVal) {
    if (newVal !== undefined && newVal[0] !== undefined) {
        if ($scope.model.curSupplier === undefined) {
            $scope.model.curSupplier = angular.copy(newVal[0].supplier_id);
            $scope.model.curCheckedImages =  angular.copy(newVal);
        }
        $scope.supplier =  angular.copy(newVal[0].supplier_id);
    }
});
Was it helpful?

Solution

By assigning one list to another you are simply copying the reference.

This means that both the models actually refer to the same list. Therefore changing any of them would reflect on the other.

Instead try this:

$scope.model2 =  angular.copy($scope.model1);

Update:

$scope.$watch('checkedImages', function (newVal) {
    if (newVal !== undefined && newVal[0] !== undefined) {
        var newObj = angular.copy(newVal);
        if ($scope.model.curSupplier === undefined) {
            $scope.model.curSupplier = newObj[0].supplier_id;
            $scope.model.curCheckedImages =  newObj;
        }
        $scope.supplier =  newObj[0].supplier_id;
    }
});

OTHER TIPS

It depends on whether you want a deep copy or shallow copy of the data in the array. For a deep copy, you can use angular.copy and for a shallow one-level-deep copy, you can use array.slice().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top