user2622344
user2622344

Reputation: 1086

AngularJS - Object assignment does not work

Good afternoon,

I have a question concering AngularJS:

In my html-template is a button:

<button class="btn btn-default" ng-click="updateData(testVar)">do it</button>

If the button is clicked, a function is fired which will update the passed $scope variable.

This variable has following structure:

$scope.testVar =
{
id: 1,
name: 'angular',
obj:
{
    obj1: 'object1',
    obj2: 'object2'
}
};

This is my function for updating the $scope variable:

$scope.updateData = function(param)
{
param = getData();
}

function getData()
{
return {
    id: 2,
    name: 'test',
    obj:
    {
        obj1: 'object3',
        obj2: 'object4'
    }
};
}

My Problem is however, after the function is finished, the $scope variable still has the same values as before.

If I update only a property of the variable, it works:

param.name = getData().name;

I don't understand how extactly that works. I would be pleased if someone could explain this process for me.

Upvotes: 1

Views: 1796

Answers (3)

Josh
Josh

Reputation: 44906

That's because you are simply swapping one reference for another. The original reference that the $scope points to is the old object.

When you update a single property, then param and $scope.testVar are still pointing to the same object, and therefore it works as you expect.

Expanding on this a bit, if we write this out in more verbose runtime speak:

When your controller initializes:

  1. Create a property called testVar on the object $scope
  2. Create an object on the heap {...} and assign a reference to it to $scope.testVar

When your function runs:

  1. Get a reference to testVar on scope and pass it into the function updateData() with the local variable name of param
  2. Execute testData() and create a new object on the heap {...}
  3. Assign a reference to the new object to the local variable param.
  4. param now points to the new object on the heap, and $scope.testVar still points to the same object it did at initialization.

[Just for posterity]

  1. Execution of updateData() finishes, and param is popped off the stack.
  2. Garbage collector sees that nothing is pointing to the object created by testData() and deletes it from the heap by deallocating the memory it took up.

Upvotes: 1

John Strickler
John Strickler

Reputation: 25421

You're replacing the reference of param with a new object instead of assigning to $scope.testVar. Do this instead:

$scope.updateData = function() {
   $scope.testVar = getData();
};

Upvotes: 1

Juan Res&#233;ndiz
Juan Res&#233;ndiz

Reputation: 97

You're just updating the param value inside functions scope, you would need to update it via $root.testData = getData();

Upvotes: 0

Related Questions