First of all,I would say sorry for my broken English and the broken codes...(many words here come from google translation...so, I\'m afraid that I can\'t make myself clear...so,
I try to avoid complex services like:
'/parents/:parent_id/children/:id'
I separate this in two services:
/parents/:parent_id/children. For GET(list) and the POST(Id in Content)
And then I have
/children/id for the PUT,DELETE and single GET
Apart that your description of the question is very complicated (tons of code), I think you missed the point of REST API concept.
You are mixing your Rails backend resources (and its routing) with client-side routing. This is wrong IMHO. Your frontend app routes shouldn't be jumping (shadowing) over REST routes.
If you are fetching users
resource (for example GET /users/5.json
) you shouldn't navigate your client to /tp/users/show
. Your REST and client-side routes are two separate, independent abstractions.
Your client-side routes should be like
/
/userprofile
/dashboard
/articles/2013?page=4
And your Controllers sitting on those routes should use your resource services to fetch required data from REST API like this:
angular.module('myApp').controller 'UserProfileController', ($scope, userResource) ->
$scope.user = userResource.query({id: SOME_ID})
angular.module('myApp.resources').factory 'userResource', ($resource) ->
params = {
id: '@id'
subItem: '@subItem'
subItemId: '@subItemId'
}
actions = {
query: {
method: 'GET'
params: {}
isArray: true
}
ban: {
method: 'POST'
params: {banned: true}
}
}
return $resource('/api-1.0/users/:id/:subItem/:subItemId', params, actions)
Well ,I figure out why the Loader for resolve doesn't work as expected... The key is that an angularjs service is a sigleton. It doesnt work because I put the loop inside the service definition in the first version...
for sort, this works:
angular.forEach [
['profile', 'profile']
['user', 'users']
['avatar', 'avatars']
],
(resouce_definition)->
resource = resouce_definition[1]
singular = resouce_definition[0]
captialize = singular.charAt(0).toUpperCase() + singular.slice(1)
app.factory("#{captialize}Loader", [
'RESTful', '$route', '$q'
(RESTful, $route, $q)->
(action)->
delay = $q.defer()
id = $route.current.params.id
fetcher = RESTful(resource)
switch action
when 'index'
fetcher.index
page: $route.current.params.page
(response, headers)->
delay.resolve
resource: response
pages: JSON.parse(headers('X-Pagination'))
(response)->
delay.reject "Unable to fetch #{resource} index"
when 'show'
fetcher.get
id: id
(response)->
delay.resolve(response)
(response)->
delay.reject "Unable to fetch #{resource} #{id}"
when 'edit'
fetcher.edit
id: id
(response)->
delay.resolve(response)
(response)->
delay.reject "Unable to fetch #{resource} #{id}"
when 'new'
fetcher.get
id: 'new'
(response)->
delay.resolve(response)
(response)->
delay.reject "Unable to fetch #{resource} new"
return delay.promise
])