2

Angular.js を使い始めたばかりで、2 つの「モデル」を「リンク」する方法がわかりません。index.php ファイルに次のコードがあります

<div ng-controller="AccountCtrl">
    <h2>Accounts</h2>
    <ul>
        <li ng-repeat="account in accounts">
            <span>{{account.id}} {{account.ownedBy}}</span>
        </li>
    </ul>
</div>
<div ng-controller="TransactionCtrl">
    <h2>Transactions</h2>
    <ul>
        <li ng-repeat="transaction in transactions">
            <span>{{transaction.id}} {{transaction.timestamp}} {{transaction.amount}} {{transaction.description}} {{transaction.account}}</span>
        </li>
    </ul>
</div>

そして次のjs

function AccountCtrl($scope, $http) {
    // initialize Data
    $http({
        method:'GET', 
        url:'http://api.mydomain.ca/accounts'
    }).success(function(data, status, headers, config) {
        $scope.accounts = data;
    }).error(function(data, status, headers, config) {
        alert('Error getting accounts. HTTP Response status code: '+status);
    });
}
function TransactionCtrl($scope, $http) {
    // initialize Data
    $http({
        method:'GET', 
        url:'http://api.mydomain.ca/transactions'
    }).success(function(data, status, headers, config) {
        $scope.transactions = data;
    }).error(function(data, status, headers, config) {
        alert('Error getting transactions. HTTP Response status code: '+status);
    });
}

したがって、私の例では、各アカウントには多くのトランザクションがあり、トランザクションに基づいてアカウントの残高を計算する関数をアカウント コントローラーに追加したいと考えていますが、異なる $scopes にあるため、その方法がわかりません。

Angular でこれを行う方法はありますか、またはアカウントを取得したときに、サーバーからの JSON 応答で「リンクされた」トランザクション情報を返す必要がありますか?

4

2 に答える 2

2

だと思いますよaccounttransactionsservice次に、アカウント/トランザクションデータを管理するための を作成できると思います。このサービスを両方のコントローラーに挿入します。

module = angular.module('app', []);

module.factory('accountService', function($http) {
  var obj = {
    // handles http communication to/from server.
    // also has methods/getters/setters for data manipulation, etc.
  };
  return obj;
});

module.controller('AccountCtrl', function($scope, accountService) {
   // access accountService for the view-databind.
});

module.controller('TransactionCtrl', function($scope, accountService) {
   // access accountService for the view-databind.
});
于 2013-01-23T21:54:13.793 に答える
1

両方の http リクエストを同時に行っているため、アカウント オブジェクトのプロパティとしてトランザクションを返すようにサービスを変更します。そうすれば、1 回のサーバー呼び出しでオーバーヘッドが少なくなり、データは必要な形式になります。最後の質問は正しい考えだと思います。

そして、Angular を使用することをお勧めします。まだ見つけていない場合は、John Lindquest がegghead.io ですばらしい一連のビデオをリリースしました。

于 2013-01-23T22:02:24.243 に答える