I've been trying out Angular JS for the past couple of days and one thing I can't figure out is how to work with relationships between models.
The project I'm working on has a Users model and an Accounts model. I have it set up on my database that each Account has a field called 'ownedBy' which is a foreign key reference to the id of the user that owns that account.
In Angular I have the following set up in a file called main.js
var myApp = angular.module('myApp', ['ngResource']);
var Users = myApp.factory('Users', function($resource) {
var User = $resource('http://api.mydomain.ca/users/:id',
{id:'@id'},
{});
return User;
});
var Accounts = myApp.factory('Accounts', function($resource) {
var Accounts = $resource('http://api.mydomain.ca/accounts/:id',
{id:'@id'},
{});
return Accounts;
});
function UsersCtrl($scope, Users) {
$scope.users = Users.query();
}
function AccountsCtrl($scope, Accounts) {
$scope.accounts = Accounts.query();
}
and the following template
<!DOCTYPE html>
<html lang=en>
<head>
<meta charset=UTF-8>
<meta http-equiv=X-UA-Compatible content=IE=edge,chrome=1>
<title>Angular Test</title>
<meta name=viewport content=width=device-width, initial-scale=1.0>
<link rel=stylesheet href=/bootstrap/css/bootstrap.min.css?v=2.2.1>
</head>
<body>
<div ng-app=myApp>
<div ng-controller=UsersCtrl>
<table class=table table-striped>
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody>
<tr ng-repeat=user in users>
<td>{{user.id}}</td>
<td>{{user.firstName}}</td>
<td>{{user.lastName}}</td>
</tr>
</tbody>
</table>
</div>
<div ng-controller=AccountsCtrl>
<table class=table table-striped>
<thead>
<tr>
<th>ID</th>
<th>Owned By</th>
</tr>
</thead>
<tbody>
<tr ng-repeat=account in accounts>
<td>{{account.id}}</td>
<td>{{account.ownedBy}}</td>
</tr>
</tbody>
</table>
</div>
</div>
<script src=http://code.jquery.com/jquery-latest.js></script>
<script src=http://ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular.min.js></script>
<script src=http://ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular-resource.min.js></script>
<script src=/bootstrap/js/bootstrap.min.js?v=2.2.1></script>
<script src=js/main.js></script>
</body>
</html>
and this is working. It pulls a JSON resource from my REST server and displays it in a table. What's the next step I need to take to end up with one table that shows users and their account numbers? (the equivalent of a database JOIN?) Is there a different way to do it for a one to many relationship? (ie... an account has many transactions)
Thanks for the help :)