过去几天我一直在尝试 Angular JS,但我不明白的一件事是如何处理模型之间的关系。
我正在处理的项目有一个用户模型和一个帐户模型。我在数据库中设置了每个帐户都有一个名为“ownedBy”的字段,该字段是对拥有该帐户的用户 ID 的外键引用。
在 Angular 中,我在名为 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();
}
以及以下模板
<!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>
这正在起作用。它从我的 REST 服务器中提取 JSON 资源并将其显示在表格中。下一步我需要采取什么措施才能得到一张显示用户及其帐号的表格? (相当于数据库 JOIN?) 对于一对多关系,是否有不同的方法? (即...一个帐户有很多交易)
感谢您的帮助:)
最佳答案
$resource
不包含任何处理服务器未处理的关系的方法,但使用 $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;
}
};
});
然后在你的 Controller 中,你可以像任何其他 promise 一样使用它:
UserService.get( $scope.userId ).then( function ( user ) {
$scope.user = user;
});
它可用于您的模板!
<div>
User: "{{user.firstName}} {{user.lastName}}" with Acct ID "{{user.acct.id}}".
</div>
关于javascript - Angular JS 模型关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14530251/