質問

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);
    }
});
役に立ちましたか?

解決

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

他のヒント

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().

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top