我有这个Rails应用程序,由UsersController提供index.html.erb。在处理该页面的角度控制器中,我为用户提供了$ resource服务
.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服务中调用的动作返回的数据。
我已经通过使用Gon ruby gem将其分配给名为Gon的全局变量来处理bootstrap数据部分。我知道我可以简单地做$ scope.users = gon.users。但是这些用户模型不会像$ scope.users [0]那样得到细节。$ save()
谢谢!
答案 0 :(得分:11)
事实证明,它非常简单!
例如,假设您在变量_tasks和角度$资源模型任务中拥有所有非角度模型,您需要做的就是将_tasks逐个传递到构造函数Task中这样:
$scope.tasks = (new Task(task) for task in _tasks)
然后每个$ scope.tasks将包含所有$ update(),$ delete()方法
$scope.tasks[0].$update({due_at: new Date})
答案 1 :(得分:1)
你想避免从User.query往返,对吧?如果是这样,那么怎么样
<html>
<script type='text/javascript>
initialUsers = <%= User.someRubyMethod.to_json %>
<script>
然后在你的控制器里面
$scope.users = intitialUsers;