Как мы можем использовать маршруты рельсов с angularjs сухим способом?

Прежде всего, я бы сказал, извините за мой сломанный английский и неработающие коды ... (многие слова здесь взяты из перевода Google ... так что ябоюсь, что смогуЯ проясняю ... я вставляю все коды ...)

Настройка маршрутов в рельсах действительно проста. Но когда мы хотим превратить это в angurjs, оно становится немного многословным ... Есть лилучшая практика » для этой работы:

учитывая некоторые рельсы ресурсов маршрута:

resources :users
resources :photos
...
resources :topics

Как это сделать с угловой стороны?

Вот как я это делаю (в сценарии с кофе, используяугловой 1.1.4):

Используйте сервис RESTful в Rails:
# angular/services/restful.js.coffee
# RESTful resource following Rails route's convention
# index:  GET  '/resource.json'
# save:   POST '/resource.json'
# get:    GET  '/resource/:id.json'
# update: PUT  '/resource/:id.json'
# edit:   GET  '/resource/:id/edit.json'
# new:    GET   just use get, id: 'new'
app.factory('RESTful', ['$resource',
  ($resource)->
    (resource_name) ->
      url = "/#{resource_name}/:id:format"
      defaults={format: '.json', id: '@id'}

      actions = {
        index:
          id: ''
          url: "/#{resource_name}:format"
          method: 'GET'
          isArray:false
        edit:
          url: "/#{resource_name}/:id/edit:format"
          method: 'GET'
        update:
          method: 'PUT'
        save:
          url: "/#{resource_name}:format"
          method: 'POST'
      }

      $resource url, defaults, actions
])

# index:  GET  '/parents/:parent_id/children.json'
# save:   POST '/parents/:parent_id/children.json'
# get:    GET  '/parents/:parent_id/children/:id.json'
# update: PUT  '/parents/:parent_id/children/:id.json'
# edit:   GET  '/parents/:parent_id/children/:id/edit.json'
# new:    GET   just use get, id: 'new'
app.factory('NESTful', ['$resource',
  ($resource)->
    (parents, children) ->
      # naive singularize
      parent = parents.replace(/s$/, '')
      url = "/#{parents}/:#{parent}_id/#{children}/:id:format"

      defaults={ format: '.json', id: '@id' }

      actions = {
        index:
          id: ''
          url: "/#{parents}/:#{parent}_id/#{children}:format"
          method: 'GET'
          isArray:false
        edit:
          url: "/#{parents}/:#{parent}_id/#{children}/:id/edit:format"
          method: 'GET'
        update:
          method: 'PUT'
        save:
          url: "/#{parents}/:#{parent}_id/#{children}:format"
          method: 'POST'
      }

      $resource url, defaults, actions
])
Маршруты:
app.config(['$routeProvider', '$locationProvider', ($routeProvider, $locationProvider) ->
  $locationProvider.html5Mode(true)

  # general RESTful routes
  resource_list = ['users', 'photos', 'topics']
  for resource in resource_list
    # naive singularize
    singular = resource.replace(/s$/, "")
    captialize = singular.charAt(0).toUpperCase() + singular.slice(1)
    $routeProvider
      .when "/#{resource}",
          templateUrl: "/tp/#{resource}/index"
          controller: "#{captialize}IndexCtrl"
          resolve:
            index: ["#{captialize}Loader", (Loader)-> Loader('index')]
      .when "/#{resource}/new",
          templateUrl: "/tp/#{resource}/edit"
          controller: "#{captialize}NewCtrl"
          resolve:
            resource: ["#{captialize}Loader", (Loader)-> Loader('new')]
      .when "/#{resource}/:id",
          templateUrl: "/tp/#{resource}/show"
          controller: "#{captialize}ShowCtrl"
          resolve:
            resource: ["#{captialize}Loader", (Loader)-> Loader('show')]
      .when "/#{resource}/:id/edit",
          templateUrl: "/tp/#{resource}/edit"
          controller: "#{captialize}EditCtrl"
          resolve:
            resource: ["#{captialize}Loader", (Loader)-> Loader('edit')]

  # special routes
  $routeProvider
    .when '/',
        templateUrl: '/tp/pages/home'
        controller: 'PageCtrl'

    .otherwise({redirectTo: '/'})
])
Контроллер должен быть супер чистым, и тогда мы можем сосредоточиться на бизнесе
app.controller 'UserShowCtrl', ['$scope', 'resource'
  ($scope, resource)->
    $scope.user = resource.user
]
app.controller 'UserIndexCtrl', ['$scope', 'index',
  ($scope, index) ->
    $scope.users = index.resource.users
    $scope.total_pages = index.pages.total_pages
    $scope.currentPage = index.pages.current_page

    getPage = (page)->
      index.resource.$index
        page: page
        (resource, headers)->
          $scope.users = resource.users

    $scope.$watch 'currentPage', (newval)->
      getPage(newval)
]
Проблема в загрузчике для разрешения obj:
app.factory('UserLoader', ['RESTful', '$route', '$q',
  (RESTful, $route, $q) ->
    (action)->
      model = 'users'
      delay = $q.defer()
      fetcher = RESTful(model)
      switch action
        when 'index'
          fetcher.index
            page: $route.current.params.page
            (resource, headers)->
              delay.resolve
                resource: resource
                pages: JSON.parse(headers('X-Pagination'))
            (resource)->
              delay.reject "Unable to fetch #{model} index"
        when 'show'
          fetcher.get
            id: $route.current.params.id
            (resource)->
              delay.resolve(resource)
            (resource)->
              delay.reject "Unable to fetch #{model} #{$route.current.params.id}"
        when 'edit'
          fetcher.edit
            id: $route.current.params.id
            (resource)->
              delay.resolve(resource)
            (resource)->
              delay.reject "Unable to fetch #{model} #{$route.current.params.id} edit"
        when 'new'
          fetcher.get
            id: 'new'
            (resource)->
              delay.resolve(resource)
            (resource)->
              delay.reject "Unable to fetch #{model} new"

      return delay.promise
])

Здесь есть 2 проблемы: первая проблема заключается в том, что я должен скопировать && вставьте приведенный выше код загрузчика и затем gsub ('пользователь ','Фото') и т. д. (просто измените 2 слова, но я ненавижу копировать && вставить ..) Я попытался переместить его в цикл, который не сделалработать, а я не могуне могу понять, почему ... Еще одна проблема заключается в том, как настроить вложенные ресурсы в СУХОЙ форме.

Наконец, спасибо за ваше терпение, и я хотел бы еще раз извиниться ... Но какое-либо решение, предложение или лучшие практики? Я делаю это неправильно?

Ответы на вопрос(3)

Ваш ответ на вопрос