1

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.

1

3 Answers 3

1

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();
};
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.