【问题标题】:Angular two $scope and splice. How to equate one to the other $scope?Angular 两个 $scope 和 splice。如何将一个等同于另一个 $scope?
【发布时间】:2013-12-05 11:57:40
【问题描述】:

问题是这样的:

$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]

为什么会这样?

更新: 解决方案:Everywhere 使用 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;
        }
    });

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

【问题讨论】:

  • 在任何地方使用angular.copy 并不是一个好主意。有时,您确实希望在更改指令中的值时修改原始对象(例如,如果您在 ng-model 中使用属性)。

标签: angularjs scope splice equals-operator


【解决方案1】:

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

这意味着两个模型实际上都引用了同一个列表。因此,改变其中任何一个都会影响另一个。

试试这个:

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

【讨论】:

  • @EvgeniyTkachenko 如果你觉得合适,欢迎用“V”接受:)
【解决方案2】:

这取决于您是想要数组中数据的深拷贝还是浅拷贝。对于深拷贝,你可以使用angular.copy,对于浅的一级深拷贝,你可以使用array.slice()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-17
    • 1970-01-01
    • 1970-01-01
    • 2016-09-14
    • 1970-01-01
    • 2015-03-03
    相关资源
    最近更新 更多