初始化AngularJS与网页JSON $资源 [英] Initializing AngularJS $resource with in-page JSON

查看:161
本文介绍了初始化AngularJS与网页JSON $资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用AngularJS'$资源获取和更新对象。为了节省页面加载一个来回,我在页面上的变量JSON对象。我怎么能与此数据初始化$资源,而不是调用$得到什么?

I'm using AngularJS' $resource to fetch and update an object. To save a round trip on page load, I have the JSON object in a variable on the page. How can I initialize the $resource with this data rather than calling $get?

推荐答案

您可以使用来创建一个 $资源创建资源的实例

You can use new to create instances of resources created with $resource:

window.somePreloadedJson = {
  id: 1,
  name: 'lancelot',
  quest: 'holy grail',
  color: 'blue',
};

app.factory('myResource', function($resource) {
  return $resource('/my/fake/:id', { id: '@id' });
});

...

$scope.resource = new myResource(window.somePreloadedJson);

下面是这种技术上的jsfiddle 的,这表明 $节省 $删除等为预期的创建的实例的工作。 (一些调试code已被添加到注销HTTP请求,而不是真正让他们,所以你可以看到的请求会在页面中​​进行了哪些。)

Here is an example of this technique on jsFiddle, which demonstrates that $save, $delete, etc. work as expected on the created instance. (Some debugging code has been added to log out HTTP requests rather than actually make them, so you can see what requests would have been made in the page.)

这篇关于初始化AngularJS与网页JSON $资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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