Reputation: 353
Here is a very simple example of what I am trying to do
Athlete.save(athlete,function(result)
{
$scope.athlete = result.athlete;
});
The issue is that the $scope.athlete variable does not update in my view. In order to get it to update I have to do this
Athlete.save(athlete,function(result)
{
$scope.athlete.fname = result.athlete.fname;
$scope.athlete.lname= result.athlete.lname;
$scope.athlete.gender= result.athlete.gender;
....
});
This gets annoying very quickly. With the first block of code it's as if angular does not know that my $scope.athlete variable has been updated. This function is triggered from an ng-click, not some jquery call, I am doing it the angular way as far as I know.
here is a simpler case I made: http://plnkr.co/edit/lMCPbzqDOoa5K4GXGhCp
Upvotes: 0
Views: 447
Reputation: 353
I received help from here to solve this: https://groups.google.com/forum/#!msg/angular/Ih06VLDH_JU/EtHLrGeMgUEJ
There are two ways, one was already mentioned and what is to use the index to update the original way.
The second way is to use angular.copy(source, destination)
Upvotes: 0
Reputation: 28016
See this answer:
https://stackoverflow.com/a/13104500/151084
Primitives are passed by value, Objects are passed by "copy of a reference".
Specifically, when you pass an object (or array) you are (invisibly) passing a reference to that object, and it is possible to modify the contents of that object, but if you attempt to overwrite the reference it will not affect the copy of the reference held by the caller - i.e. the reference itself is passed by value.
This explains why plunker doesn't update. However, your inline code example (where you use $scope.athlete = result.athlete
) seems like it should work. Can you create a sample showing that failing?
Upvotes: 0
Reputation: 1173
athlete = { fname: 'new fname', lname: 'new lname' };
seems to be creating a new local variable called athlete
, instead of updating the one you are passing.
A better way to handle this would be to pass the $index
of the athlete
to the updateAthlete()
function and do the following:
$scope.updateAthlete = function (index) {
$scope.athletes[index] = {
fname: 'new fname',
lname: 'new lname'
};
};
EDIT: see working plunkr: http://plnkr.co/edit/KPu3CSvGIl8l581r9A5o?p=preview
Upvotes: 1