Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS Services (Update/Save)

New to AngularJS and trying to get a grasp of the framework, and trying to build a basic CRUD app. I can't seem to figure out what is needed to Update an existing record. Here is my service:

 angular.module('appServices', ['ngResource']).
factory('App', function ($resource) {
    var Item = $resource('App/:AppId', {
        //Default parameters
        AppId: '@id'
    }, {
        //Actions
        query: {
            method: 'GET',
            isArray: true
        },
        getById: {
            method: 'PUT'
        },
        update: {
            method: 'POST'
        }
    });
    return Item;
});

I can run a basic Get all query, and getById to populate an edit form, but that's where I'm stuck. Here is example code for getById

 $scope.apps = App.query();

$scope.getEdit = function(AppId) {
    App.getById({id:AppId}, function(app) {
        $scope.original = app;
        $scope.app = new App(app);
    });
};

$scope.save = function() {
    //What type of information should go here?
    //Do I need to make changes to the appServices?
};

I guess, I'm just not sure what's next concerning Updating existing information, or how the "app" object gets passed to the API, can anyone point me in the right direction, or show me a quick update method?

like image 577
Logan W Avatar asked Aug 20 '12 19:08

Logan W


1 Answers

This is a really messy way of handling save operations in angular. For one - you should not be using PUT operations for retrieval requests and secondly - all of this is already built-in to angular. See below.

var Item = $resource( 'App/Details/:AppId', { AppId: '@id' } );

var item = Item.get({ id: 1 }, function( data ) {
    data.setAnothervalue = 'fake value';
    data.$save();
);

What I'm doing here is retrieving an "Item" and then immediately saving it with new data once it's returned.

Angular JS provides a stack of defaults already, including query, save, remove/delete, get.etc. And for most RESTful APIs, you really shouldn't need to add much, if anything at all. See the resource docs for more information, particularly the information on defaults: http://docs.angularjs.org/api/ngResource.$resource

Additionally, once you get a handle on that - you may want to use $save for both create/update operations, but using POST/PUT (RESTful conventions). If you do, see my article that I wrote about not too long ago: http://kirkbushell.me/angular-js-using-ng-resource-in-a-more-restful-manner/

like image 190
Oddman Avatar answered Sep 18 '22 02:09

Oddman