2013-01-23 113 views
2

我剛剛開始使用Angular.js,我不確定如何將兩個「模型」「鏈接」在一起。我在我的index.php文件在Angular.js中連接模型

<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); 
    }); 
} 

所以在我的例子中,每個帳戶將有許多事務,我想一個函數添加到我的帳戶控制器根據交易計算帳戶的餘額,但我不知道如何執行此操作,因爲它們處於不同的$範圍內。

有沒有辦法在Angular中做到這一點,或者當我得到帳戶時,是否必須從服務器返回JSON響應中的「鏈接」事務信息?

回答

2

我猜account包含transactions,對吧? 然後我想,您可以創建一個service來管理帳戶/交易數據。 將這項服務注入兩個控制器。

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. 
}); 
1

由於您同時提出了兩個http請求,所以我會更改我的服務以返回作爲帳戶對象屬性的事務。那麼這將是一個服務器調用,更少的開銷,並且您的數據將以您需要的格式存在。我認爲您對最後一個問題有正確的想法。

使用Angular的好選擇。如果你還沒有找到他們,John Lindquest在egghead.io發佈了一系列很棒的視頻。