Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS $resource creating new object instead of updating object

Tags:

rest

angularjs

// Set up the $resource
$scope.Users = $resource("http://localhost/users/:id");

// Retrieve the user who has id=1
$scope.user = $scope.Users.get({ id : 1 }); // returns existing user

// Results
{"created_at":"2013-03-03T06:32:30Z","id":1,"name":"testing","updated_at":"2013-03-03T06:32:30Z"}

// Change this user's name
$scope.user.name = "New name";

// Attempt to save the change 
$scope.user.$save();

// Results calls POST /users and not PUT /users/1
{"created_at":"2013-03-03T23:25:03Z","id":2,"name":"New name","updated_at":"2013-03-03T23:25:03Z"}

I would expect that this would result in a PUT to /users/1 with the changed attribute. But it's instead POST to /users and it creates a new user (with a new id along with the new name).

Is there something that I'm doing wrong?

AngularJS v1.0.5
like image 424
Mark Peterson Avatar asked Mar 03 '13 23:03

Mark Peterson


1 Answers

you just need to tell the $resource, how he has to bind the route-parameter ":id" with the JSON Object:

$scope.Users = $resource("http://localhost/users/:id",{id:'@id'});

This should work, regards

like image 54
kfis Avatar answered Oct 24 '22 10:10

kfis