Chris
Chris

Reputation: 798

AngularJS is setting value for unrelated scope variable

I have the following angular code to initialize an angular form. It returns a mostly null record except for a couple of dates and employee info.

I was trying to create a scope variable to keep the original record for comparison purposes after the form is filled out. This is what $scope.TechSheetInfoStatic is for.

For our purposes here, I set $scope.TechSheetInfo.Customer.Email to a dummy value. This, while updating $scope.TechSheetInfo, also updates $scope.TechSheetInfoStatic. Why?

     $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 = "[email protected]";
            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);
    };

Upvotes: 1

Views: 63

Answers (1)

georgeawg
georgeawg

Reputation: 48968

Use angular.copy to make a deep 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 = "[email protected]";
        alert(JSON.stringify($scope.TechSheetInfo.Customer));
        alert(JSON.stringify($scope.TechSheetInfoStatic.Customer));
    };

Since response.data is an object. The assignment statement assigns a reference value to the variable. The angular.copy function will create a new object and copy the contents to the new object.

A variable holding an object does not "directly" hold an object. What it holds is a reference to an object. When you assign that reference from one variable to another, you're making a copy of that reference. Now both variables hold a reference to an object. Modifying the object through that reference changes it for both variables holding a reference to that object.

For more information, see Pass-by-reference JavaScript objects.

Upvotes: 1

Related Questions