Reputation: 1086
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
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:
testVar
on the object $scope
{...}
and assign a reference to it to $scope.testVar
When your function runs:
testVar
on scope and pass it into the function updateData()
with the local variable name of param
testData()
and create a new object on the heap {...}
param
.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]
updateData()
finishes, and param
is popped off the stack.testData()
and deletes it from the heap by deallocating the memory it took up.Upvotes: 1
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
Reputation: 97
You're just updating the param value inside functions scope, you would need to update it via $root.testData = getData();
Upvotes: 0