jassok
jassok

Reputation: 421

Angular JS $scope, databinding, and variables changing.

So I have an APP I'm working on in Angular JS v1.4.0 and I'm running into a scoping issue. There's a section that has a form that needs to be submitted, but the data needs to be modified before its sent over. I'm currently trying to do this in the javascript before making the call to the server.

I have $scope.msgEditor, that is an object of a bunch of different values that are necessary for the form, as well as the message variables itself. The important part looks something like this:

msgEditor [
    msg: {
        groups: {
            selected: {
                0: '1',
                1: '2',
            }
        }
    }
]

I'm trying to take this $scope variable, assign it to a local variable, and begin parsing the data like such:

$scope.formOnSubmit = function () {
    formattedMessage = formatDataForSave($scope.msgEditor.msg);
};

function formatDataForSave(message) {
    message.groups = message.groups.selected.join(', ');

    return message;
}

What I want to happen, is $scope.msgEditor.msg to not change at all, and formattedMessage to be returned from the second function, so it can be placed into a $http call. However, the join changes message, formattedMessage, AND $scope.msgEditor.msg

I did a bit more testing, to see what was happening:

$scope.formOnSubmit = function () {
    $scope.test = $scope.msgEditor.msg;
    var formattedMessage = $scope.test;
    formattedMessage = formatDataForSave(formattedMessage);
};

And found that the change made to formattedMessage, would change $scope.test, which would change $scope.msgEdtior.msg.

Any direction on why this is happening, or how to prevent it would be amazing.

Upvotes: 1

Views: 48

Answers (1)

Carlos
Carlos

Reputation: 243

I believe you are confusing about passing arguments into functions in javascript: in javascript all arguments are passed by reference so the consequence is what you are experiencing. Have a look at angular.copy function.

https://code.angularjs.org/1.3.17/docs/api/ng/function/angular.copy

I cannot test this but you could try:

$scope.formOnSubmit = function () {
    var msgCopy = angular.copy($scope.msgEditor.msg);
    formattedMessage = formatDataForSave(msgCopy);
};

function formatDataForSave(message) {
    message.groups = message.groups.selected.join(', ');

    return message;
}

Upvotes: 1

Related Questions