我想映射默认的AngularJS $ resource操作:
'get': {method:'GET'}
'save': {method:'POST'}
'query': {method:'GET', isArray:true}
'remove': {method:'DELETE'}
'delete': {method:'DELETE'}
这5条RESTful路线:
'show': {method:'GET'} -> get
'create': {method:'POST'} -> save
'update': {method:'PUT'} -> save
'index': {method:'GET', isArray:true} -> query
'delete': {method:'DELETE'} -> remove or delete
除了
save
之外,其他所有内容都映射良好。它作为create
请求在POST
上工作。但是我要在保存具有PUT
的资源时将其更改为id != null
请求# This factory needs a smarter $save() method
myServices.factory 'Message', ['$resource', ($resource) ->
Message = $resource "api/users/:user_id/messages/:id",
user_id: '@user_id'
id: '@id'
,
# update should not be needed
update:
method: 'PUT'
Message
]
myApp.controller "UsersShowCtrl", ["$scope", "$routeParams", "User", "Message", ($scope, $routeParams, User, Message) ->
$scope.user = User.get({id: $routeParams.user_id})
$scope.myMessage = new Message {user_id: $routeParams.user_id}
$scope.submitMyMessage = ->
# This should just be:
# $scope.myMessage.$save()
# rather than:
unless $scope.myMessage.id?
$scope.myMessage.$save()
else
$scope.myMessage.$update()
]
我最终还是想修改提交的参数,以便可以将它们命名为默认的Rails嵌套参数,即
params[:message]
,而不是将它们直接附加到根params
字符串,但是首先我需要知道如何最好地修改$资源。 最佳答案
我的头顶上,这个save()方法怎么样?
myServices.factory 'Message', ['$resource', ($resource) ->
Message = $resource "api/users/:user_id/messages/:id",
user_id: '@user_id'
id: '@id'
,
# update should not be needed
update:
method: 'PUT'
Message::save = ->
if @id?
@update()
else
@create()
Message
]
关于javascript - 扩展AngularJS $ resource以映射到Rails RESTful路线(特别是$ save以创建和更新),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15176185/