angular js model relationships angular js model relationships javascript javascript

angular js model relationships


$resource doesn't contain any way to deal with relationships that aren't handled by the server, but it's pretty simply with $http:

module.factory( 'UserService', function ( $http, $q ) {  return {    get: function getUser( id ) {      // We create our own promise to return      var deferred = $q.defer();      $http.get('/users/'+id).then( function ( user ) {        $http.get('/accounts/'+user.id).then( function ( acct ) {          // Add the account info however you want          user.account = acct;          // resolve the promise          deferred.resolve( user );        }, function getAcctError() { deferred.reject(); } );      }, function getUserError() { deferred.reject(); } );      return deferred.promise;    }  };});

And then in your controller, you can just use it like any other promise:

UserService.get( $scope.userId ).then( function ( user ) {  $scope.user = user;});

And it's available for your template!

<div>    User: "{{user.firstName}} {{user.lastName}}" with Acct ID "{{user.acct.id}}".</div>


I use js-data if I need relationships in the UI. The library handles relationships and data modelling pretty elegantly in general. I have found it easier to use even if you are just looking for a nice API interface. I prefer it to ngResource.

In your case you would have a model for User and model for Account

src/app/data/account.model.coffee

angular.module 'app.data' #this can be your module name  .factory 'Account', (DS) ->    DS.defineResource      name: 'account'      endpoint: 'accounts'      relations:        belongsTo:          user:            localKey: 'userId'            localField: 'user'

src/app/data/user.model.coffee

angular.module 'app.data'  .factory 'User', (DS) ->    DS.defineResource      name: 'user'      endpoint: 'users'      relations:        belongsTo:          account: #make sure this matches the 'name' property of the other model            foreignKey: 'userId'            localField: 'account'