Alex Rivera | Logout

AngularJS: Creating Objects that map to REST Resources (ORM-Style)

Asked 2013-04-24T08:18:41.220
64

I'm pretty new to AngularJS, but I'm pretty unclear on how to tie it up to my Server's REST Api backend.

For example, say I have an "image" resource that I get by GET-ing: myApi/image/1/. This returns a json object with various fields. Let's say something like:

{url: "some/url", date_created: 1235845}

Now, I want some kind of representation in my AngularJS app of this "Image" object. This representation is more than just a mapping of the fields - I want to add "helper" functions, for example a function that converts the date_create field into something human-readable.

I know about the $resource service, but I'm unclear what I need to do to create a basic "class" in Angular, that uses Resource to get the JSON object, but then enhances it by adding various helper functions.

Bonus points:

I'm also unclear how to add "relationships" between models. For example, I might have a "user" resource that has embedded inside it an "image" resource, and I'll want to grab the User resource, but be able to call "Image" helper functions on the "Image" part of the model.

Edit
Report

2 Answers

15

I'm creator of Restangular so my opinion can be biased.

But as Bob said, you can use Restangular for it.

Restangular uses your Restful API Resources to go over the tree. You can also add new methods to this.

This is coding example: https://github.com/mgonto/restangular#lets-code

And this way you can add new methods to your object (The bonus points :)) https://github.com/mgonto/restangular#creating-new-restangular-methods

Hope this works out for you :).

Otherwise, you can also use ngResource ($resource) for this but in my opinion, it needs some "love" and "sugar".

Bests

answered 2013-05-09T22:57:43.140
4

ModelCore ( https://github.com/klederson/ModelCore ) works pretty much like this, and is very very easy to implement:

var ExampleApp = angular.module('ExampleApp', ['ModelCore']); //injecting ModelCore

ExampleApp.factory("Users",function(ModelCore) {
  return ModelCore.instance({
    $type : "Users", //Define the Object type
    $pkField : "idUser", //Define the Object primary key
    $settings : {
      urls : {
        base : "http://myapi.com/users/:idUser",
      }
    },
    $myCustomMethod : function(info) { //yes you can create and apply your own custom methods
        console.log(info);
    }
  });
});

//Controller
function MainCrtl($scope, Users) {
  //Setup a model to example a $find() call
  $scope.AllUsers = new Users();

  //Get All Users from the API
  $scope.AllUsers.$find();

  //Setup a model to example a $get(id) call
  $scope.OneUser = new Users();

  //Hey look there are promisses =)
  //Get the user with idUser 1 - look at $pkField
  $scope.OneUser.$get(1).success(function() {
    console.log("Done!",$scope.OneUser.$fetch());
});
answered 2013-05-21T14:31:15.760

Your Answer