Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing an angular resource object instance without calling the server

In Backbone.js, one can instantiate a model with pre-existing JSON data by using

var user = new Backbone.Model({ name: "John Doe", age: 30 });

And then perform updates with a single call

user.save({ age: 31 }, { success: successCallback, error: errorCallback });

This comes handy in all sorts of scenarios, such as when that data is already available on the client through caching or pre-populated templates (like using <%= raw @user.to_json %> in rails erb templates).

I'm curious to know how this is done when using $resource with Angular.js. Right now, I have a situation where my data is cached on the client before the $resource is created, and I'd like to update it without making an extra GET call to populate the object:

app.factory('User', ['$resource', function($resource) {
    return $resource('/users/:user_id.json', { user_id: '@id' }, {
        get: { method: 'GET' },
        save: { method: 'PUT' },
        create: { method: 'POST' },
        destroy: { method: 'DELETE' }
    });
}]);

And somewhere in my controller I'd like to just update an existing user without fetching it from the server:

app.controller('UsersController', ['User', function(User) {
    // somehow initialize a user from an existing
    // object, say { name: "John Doe", age: 30 }
    user.age = 31
    user.$save()

    // instead of doing this
    User.get({ user_id: 100 }, function(user, respHeaders) {
        user.age = 31
        user.$save()
    }); 
}]);

I'm probably still in the Backbone mindset, but I'm really curious if I'm approaching this all wrong. Thanks.

like image 724
sa125 Avatar asked Jun 25 '13 10:06

sa125


1 Answers

$resource gives the option to create a new user like you would with any object:

var user = new User({name : 'John Doe', age: 30});
user.age = 32;
user.$save();

Resource Docs

like image 88
Narretz Avatar answered Nov 16 '22 10:11

Narretz