Something strange is happening in my code. I created a function called "insertTstData" outside of any angular scope, and when it is called from another function named "save" within a controller named "remark", it somehow manipulates a local variable and the change reflects across all variables with the same content, even those not directly related.
This situation is so absurd that I find it difficult to explain without giving you the full context.
Here's how it all starts: I use the $http service to retrieve a JSON configuration file and store it in a scope variable while inside the "main" controller (the parent of the problematic "remark" controller):
$http.get(path + 'remarkConfig.json')
.then(function (response) {
//modify fields
$scope.remark = response.data; //this variable will be used later on
$scope.dummy = response.data; //this variable gets changed unexpectedly
});
Although these variables are arrays of objects, let's simplify them as objects with two properties for now:
{"p1":"PROP ONE", "p2": "PROP TWO"}
There's a button within the "remark" controller that triggers the save function passing $scope.remark to it:
<md-button class="amaButton md-raised" ng-click="save(data, remark)" aria-label="save">{{translate.save}}</md-button>
Below is the save function within the "remark" controller's scope which also has access to the "main" scope:
$scope.save = function (data, remarks) {
console.log($scope.dummy);
console.log($scope.remark);
console.log(remarks);
var originalRemarks = {};
originalRemarks.codes = remarks;
//insert TSTs into data, formatting <>-like remarks
var response = insertTstData(data, $scope.tst, remarks);
console.log($scope.dummy);
console.log($scope.remark);
console.log(remarks);
console.log(originalRemarks.codes);
}
Now, let's take a look at the troublesome function insertTstData (outside any controller/scope):
function insertTstData(data, tst, remarks) {
var rem = remarks;
rem.p1="";
var response={"data": data, "remarks": rem};
return response;
}
//after this function executes, every variable's p1 is set to an empty string!
I have thoroughly checked the code and cannot find any other changes being made to these variables elsewhere. Could they all be pointing to the same value due to some unknown mechanic?