如何引导数据,因为它是由 Angular.js 中的 $resource 服务获取的 [英] How to bootstrap data as it it were fetched by a $resource service in Angular.js
问题描述
我有一个由 UsersController 提供 index.html.erb 的 Rails 应用程序.在处理该页面的角度控制器中,我为用户提供了一个 $resource 服务
I have this Rails app that serves an index.html.erb by a UsersController. In the angular controller that handles that page, I have a $resource service for the User
.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'
])
控制器获取
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..
我认为这是一种非常常见的情况,但显然仅此页面就需要多次访问服务器.我想知道 Angular 是否有办法使用一些引导程序数据,因为它们是从 $resource 服务中调用的操作返回的数据.
I think this is a pretty common scenario, but clearly it takes more than one trip to the server for just this page. I was wondering if there's a way for Angular to use some bootstrap data as it they were returned data from an action called in a $resource service.
我已经通过 Gon ruby gem 将引导程序数据部分分配给一个名为 Gon 的全局变量来处理它.我知道我可以简单地做 $scope.users = gon.users.但是这些用户模型将无法获得像 $scope.users[0].$save()
I have already taken care of the bootstrap data part by assigning it to a global variable called Gon with the Gon ruby gem. I know I could simply do $scope.users = gon.users. But then these users models won't get the niceties like $scope.users[0].$save()
谢谢!
推荐答案
事实证明,这真的很简单!
As it turns out, it's really simple!
例如,假设您在变量 _tasks 和 angular $resource 模型 Task 中拥有所有非角度模型,您需要做的就是将 _tasks 一一传递到构造函数 Task 中,如下所示:>
For instances, let's say you have all your non-angular models in a variable _tasks and the angular $resource model Task, all you need to do is pass the _tasks one by one into the constructor function Task like this:
$scope.tasks = (new Task(task) for task in _tasks)
那么每个 $scope.tasks 都会有所有这些 $update(), $delete() 方法
then each of the $scope.tasks will have all those $update(), $delete() methods
$scope.tasks[0].$update({due_at: new Date})
这篇关于如何引导数据,因为它是由 Angular.js 中的 $resource 服务获取的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!