【问题标题】:AngularJS is setting value for unrelated scope variableAngularJS 正在为不相关的范围变量设置值
【发布时间】:2019-04-16 14:04:57
【问题描述】:

我有以下角度代码来初始化角度形式。它返回一个大部分为空的记录,除了几个日期和员工信息。

我试图创建一个范围变量来保留原始记录,以便在填写表格后进行比较。这就是 $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);
    };

【问题讨论】:

    标签: angularjs variables scope


    【解决方案1】:

    使用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 是一个对象。赋值语句为变量分配一个引用值。 angular.copy 函数将创建一个新对象并将内容复制到新对象中。

    持有对象的变量并不“直接”持有对象。它持有的是对对象的引用。当您将该引用从一个变量分配给另一个变量时,您正在制作该引用的副本。现在两个变量都持有一个对象的引用。通过该引用修改对象会更改持有对该对象的引用的两个变量。

    如需了解更多信息,请参阅Pass-by-reference JavaScript objects

    【讨论】:

    • 好的...谢谢!我什至没有考虑到这一点。使用引用值更改任何对象会更改该对象的所有出现。现在我可以回家了。
    猜你喜欢
    • 2018-12-21
    • 2018-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-01
    • 2013-09-23
    • 2013-07-23
    • 1970-01-01
    相关资源
    最近更新 更多