Kris Braun Kris Braun - 1 year ago 57
AngularJS Question

Initializing AngularJS $resource with in-page 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);

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