如何引导数据,因为它是由Angular.js中的$ resource服务获取的

Nik*_* So 10 angularjs

我有这个Rails应用程序,由UsersController提供index.html.erb.在处理该页面的角度控制器中,我为用户提供了$ resource服务

CoffeeScript的

.factory('User', ['$resource', ($resource) ->
  $resource 'api/users/:user_id/:action', {authenticity_token:app.csrf},
    query:
      method: 'GET'
      isArray: yes
    new:
      method: 'GET'
      params:
        user_id: 'new'
    update:
      method: 'PUT'
])
Run Code Online (Sandbox Code Playgroud)

并且控制器取出

window.app = angular.module("app", ['userServices'])
.config(["$routeProvider", ($routeProvider) ->
  $routeProvider
  .when "/users",
    templateUrl: "assets/templates/users/index.html"
    controller: UserCtrl

  .otherwise redirectTo: "/users"
])

# users Controllers
UserCtrl = ($scope, User) ->
  User.query (r) ->
    $scope.users = r
    # code..
Run Code Online (Sandbox Code Playgroud)

我认为这是一个非常常见的情况,但很明显,只需要这个页面就需要多次访问服务器.我想知道Angular是否有办法使用某些引导数据,因为它们是从$ resource服务中调用的动作返回的数据.

我已经通过使用Gon ruby​​ gem将其分配给名为Gon的全局变量来处理引导数据部分.我知道我可以简单地做$ scope.users = gon.users.但是这些用户模型不会像$ scope.users [0]那样得到细节.$ save()

谢谢!

Nik*_* So 11

事实证明,它真的很简单!

例如,假设您在变量_tasks和angular $ resource模型Task中拥有所有非角度模型,您需要做的就是将_tasks逐个传递到构造函数Task中,如下所示:

$scope.tasks = (new Task(task) for task in _tasks)
Run Code Online (Sandbox Code Playgroud)

然后每个$ scope.tasks将拥有所有$ update(),$ delete()方法

$scope.tasks[0].$update({due_at: new Date})
Run Code Online (Sandbox Code Playgroud)