angularjsscopespliceequals-operator

Angular two $scope and splice. How to equate one to the other $scope?


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

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