【问题标题】:why two $scopes updates at the same time, duplicate data为什么两个 $scopes 同时更新,重复数据
【发布时间】:2015-02-15 03:35:44
【问题描述】:

我有这段代码

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

我想将数据从一个对象推送到另一个对象(item 到 item2),效果很好,但是当我从 item 更改数据时 item2 也会更新我不想要这个。

我错过了什么?

【问题讨论】:

  • 顺便说一句,if (tempItem[index].validate == true)if (tempItem[index].validate) 的含义相同。如果你想比较严格等于布尔真,你应该使用if (tempItem[index].validate === true)

标签: javascript angularjs angularjs-scope javascript-objects


【解决方案1】:

使用angular.copy按价值应对

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

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

【讨论】:

    【解决方案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);
                    }
                }
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-17
      • 2020-04-04
      • 1970-01-01
      • 1970-01-01
      • 2017-07-17
      • 2021-03-18
      • 1970-01-01
      相关资源
      最近更新 更多