如何引导数据,因为它是由一个Angular.js $资源服务获取 [英] How to bootstrap data as it it were fetched by a $resource service in Angular.js

查看:129
本文介绍了如何引导数据,因为它是由一个Angular.js $资源服务获取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的Rails应用程序,通过一个UsersController供应的index.html.erb。在角控制器处理该页面中,我有一个$资源服务为用户

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..

我觉得这是一个pretty常见的情况,但显然它需要一个以上的行程到服务器只是这个页面。我在想,如果有一种方式,角度使用,因为它他们从所谓的在$资源服务的操作返回的数据引导的一些数据。

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.

我已经将其分配到一个名为同坤红宝石创业板刚全局变量照顾引导数据部分。我知道我可以简单地做$ scope.users = gon.users。但随后这些机型的用户不会得到像$ scope.users [0]细微之处。$保存()

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和角$资源模型任务所有的无棱角型号,所有你需要做的是通过_tasks逐个放入构造函数任务是这样的:

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将有所有这些更新$(),$删除()方法

then each of the $scope.tasks will have all those $update(), $delete() methods

$scope.tasks[0].$update({due_at: new Date})

这篇关于如何引导数据,因为它是由一个Angular.js $资源服务获取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆