Angular两个$ scope和splice。如何将一个与另一个$ scope相提并论?

时间:2013-11-21 06:13:05

标签: angularjs scope splice equals-operator

问题在于:

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

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

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

返回:

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

需要:

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

为什么会这样?

更新 解决方案:无处不在使用 angular.copy($scope.val) 我的代码不好:

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

2 个答案:

答案 0 :(得分:2)

通过将一个列表分配给另一个列表,您只需复制引用。

这意味着两个模型实际上都引用了相同的列表。因此,改变它们中的任何一个都会反映出另一个。

而是试试这个:

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

<强>更新

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

答案 1 :(得分:1)

这取决于您是否需要数组中数据的深层复制浅层复制。对于深层副本,您可以使用angular.copy,对于浅层单层深度副本,您可以使用array.slice()