AngularJS $资源创建新对象而不是更新对象

Mar*_*son 7 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"}
Run Code Online (Sandbox Code Playgroud)

我希望这会导致带有更改属性的PUT到/ users/1.但它改为POST/users,它会创建一个新用户(新ID和新名称).

有什么我做错了吗?

AngularJS v1.0.5
Run Code Online (Sandbox Code Playgroud)

kfi*_*fis 8

你只需要告诉$资源,他如何将路由参数":id"与JSON对象绑定:

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

这应该工作,问候

  • 回答我关于PUT而不是POST的问题,$ resource("/ users /:id",{'id':'@ id'},{update:{method:'PUT'}}); PUT的诀窍.只需以User.save(用户)和用户.$ save的方式调用User.update(用户)或用户.$ update. (15认同)