5

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.

1 Answer 1

12

$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

Sign up to request clarification or add additional context in comments.

2 Comments

Wow, missed that one. Thanks!
Is it possible to initialize array of user resources ? (without using any loop to create resource instance one by one)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.