Reputation: 520
I have 3 api endpoints
[{"id":"1", "name":"Bank 1", "starting_balance":"0.00"},{"id":"2", "name":"Bank 2", "starting_balance":"10.83"}]
into $scope.acc
[{"id":"1", "amount":"400.00"},{"id":"2", "amount":"500.00"}]
into $scope.expense
[{"id":"1", "amount":"1000.00"},{"id":"2", "amount":"1000.00"}]
into $scope.income
I don't know how to combine these three data. Here is my HTML code:
<tr>
<td>Account Name</td>
<td>Starting Balance</td>
<td>Income</td>
<td>Expense</td>
</tr>
<tr ng-repeat="a in acc">
<td>{{a.name}}</td>
<td>{{a.starting_balance}}</td>
<td></td>
<td></td>
</tr>
Upvotes: 0
Views: 125
Reputation: 6486
It sounds like you are trying to make 3 AJAX calls and then combine all the results together. It might be better just to aggregate this information in the API that you call instead of trying to fix this client-side.
But if you're stuck with the API and have to do this client-side, I suggest using $q.all
to combine the 3 separate promises (from the API calls) into a single post-processing function.
For example, in your controller code:
$q.all([api.getAccount(), api.getExpense(), api.getIncome()])
.then(combineInformation);
function combineInformation(apiResults) {
var accountInfo = apiResults[0]; //result of getAccount()
var expenseInfo = apiResults[1]; //result of getExpense()
var incomeInfo = apiResults[2]; //result of getIncome()
var aggregateInfo = accountInfo.map(buildInfo);
function buildInfo(account) {
var info = {
id: account.id,
account: account
};
info.expense = expenseInfo.find(function (e) { return e.id === info.id; });
info.income = incomeInfo.find(function (i) { return i.id === info.id; });
return info;
}
$scope.arr = aggregateInfo;
}
Upvotes: 1
Reputation: 41387
combine the arrays using map operator.
Demo
angular.module('app',[])
.controller('ctrl',function($scope){
$scope.income = [{"id":"1", "amount":"1000.00"},{"id":"2", "amount":"1000.00"}]
$scope.expense = [{"id":"1", "amount":"400.00"},{"id":"2", "amount":"500.00"}]
$scope.acc = [{"id":"1", "name":"Bank 1", "starting_balance":"0.00"},{"id":"2", "name":"Bank 2", "starting_balance":"10.83"}]
$scope.arr = $scope.acc.map((item) => {
var exp = $scope.expense.find((ex) => ex.id === item.id)
var inc = $scope.income.find((ins) => ins.id === item.id)
return {
acc : item,
inc : inc,
exp : exp
}
})
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<table>
<tr>
<td>Account Name</td>
<td>Starting Balance</td>
<td>Income</td>
<td>Expense</td>
</tr>
<tr ng-repeat="a in arr">
<td>{{a.acc.name}}</td>
<td>{{a.acc.starting_balance}}</td>
<td>{{a.inc.amount}}</td>
<td>{{a.exp.amount}}</td>
</tr>
</table>
</div>
Upvotes: 1