代码之家  ›  专栏  ›  技术社区  ›  Chris

AngularJS是无关范围变量的设置值

  •  1
  • Chris  · 技术社区  · 7 年前

    我有下面的angular代码来初始化angular表单。它返回一个几乎为空的记录,除了几个日期和员工信息。

    我试图创建一个范围变量,以便在填写表单后保留原始记录以进行比较。这就是$scope.TechSheetInfoStatic的用途。

    出于我们在这里的目的,我将$scope.TechSheetInfo.Customer.Email设置为一个虚拟值。在更新$scope.TechSheetInfo时, 还更新了$scope.TechSheetInfoStatic . 为什么?

         $scope.initializeTechSheet = function() {
            $scope.TechSheetInfo = [];
            $scope.TechSheetInfoStatic = [];
            $scope.customerIDDisabled = false;
            $scope.orderIDDisabled = false;
    
            const successFunction = function(response) {
                $scope.TechSheetInfo = response.data;
                $rootScope.customerInfo = response.data.Customer;
                $scope.TechSheetInfoStatic = response.data;
                $scope.TechSheetInfo.Customer.Email = "bobo@bobo.com";
                alert(JSON.stringify($scope.TechSheetInfo.Customer));
                alert(JSON.stringify($scope.TechSheetInfoStatic.Customer));
    
            };
    
            const failureFunction = function(response) {
                //console.log('Error' + response.status);
            };
    
            TechSheetFactory.ITS(successFunction, failureFunction);
        };
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   georgeawg    7 年前

    使用 angular.copy

       const successFunction = function(response) {
            $scope.TechSheetInfo = response.data;
            $rootScope.customerInfo = response.data.Customer;
            ̶$̶s̶c̶o̶p̶e̶.̶T̶e̶c̶h̶S̶h̶e̶e̶t̶I̶n̶f̶o̶S̶t̶a̶t̶i̶c̶ ̶=̶ ̶r̶e̶s̶p̶o̶n̶s̶e̶.̶d̶a̶t̶a̶;̶
            $scope.TechSheetInfoStatic = angular.copy(response.data);
            $scope.TechSheetInfo.Customer.Email = "bobo@bobo.com";
            alert(JSON.stringify($scope.TechSheetInfo.Customer));
            alert(JSON.stringify($scope.TechSheetInfoStatic.Customer));
        };
    

    自从 response.data 复印件 函数将创建一个新对象并将内容复制到新对象。

    Pass-by-reference JavaScript objects .

    推荐文章