为什么两个$scopes同时更新,重复数据

why two $scopes updates at the same time, duplicate data

本文关键字:更新 数据 scopes 两个 为什么      更新时间:2023-09-26

我有这段代码

  $scope.addToOrder = function(index) {
        var tempItem = $scope.item;
        if (tempItem[index].validate == true){
            if (_.isEmpty($scope.item2) == true) {
                $scope.item2.push(tempItem[index]);
            } else {
                for (var i = 0; i < $scope.item2.length; i++) {
                    if ($scope.item2[i] == tempItem[index]) {
                        break;
                    }
                    if (i == $scope.item2.length - 1) {
                        $scope.item2.push(tempItem[index]);
                    }
                }
            }
        }
    }

我想将数据从一个对象推送到另一个对象(项目到项目2),它运行良好,但是当我从项目更改数据时,项目2更新我不希望这样。

我错过了什么?

照原样,您使用的是对象引用。然后,如果修改一个,则其他一个也会被修改。

您可以使用angular.copy

$scope.addToOrder = function(index) {
    var tempItem = $scope.item;
    var itemCopy = angular.copy(tempItem[index]);
    if (tempItem[index].validate == true){
        if (_.isEmpty($scope.item2) == true) {
            $scope.item2.push(itemCopy);
        } else {
            for (var i = 0; i < $scope.item2.length; i++) {
                if ($scope.item2[i] == tempItem[index]) {
                    break;
                }
                if (i == $scope.item2.length - 1) {
                    $scope.item2.push(itemCopy);
                }
            }
        }
    }
}

使用 angular.copy 按值处理

 angular.copy($scope.item1, $scope.item2);

 $scope.item1 = angular.copy($scope.item2);