As I delve into learning angularjs (not 2), one of the challenges I face is calculating the total amount for a customer order. The data I'm working with is structured as follows:
var clients = [
{
id: 1,
joined: '2000-12-02',
name:'John',
city:'Chandler',
orders: [
{
id: 1,
product: 'Shoes',
total: 9.9956
}
]
},
{
id: 2,
joined: '1965-01-25',
name:'Zed',
city:'Las Vegas',
orders: [
{
id: 2,
product: 'Baseball',
total: 9.995
},
{
id: 3,
product: 'Bat',
total: 9.995
}
]
}
]
With a controller and factory in place to handle this data...
Here's how my controller code looks like:
(function() {
var ClientsController = function ($scope, $log, clientFactory) {
$scope.sortBy = 'name';
$scope.reverse = false;
$scope.clients = [];
function initialize () {
clientFactory.getClients()
.success(function(clients) {
$scope.clients = clients;
})
.error(function(data, status, headers, config){
$log.log(data.error + ' ' + status );
});
}
initialize();
$scope.doSort = function(propName) {
$scope.sortBy = propName;
$scope.reverse = !$scope.reverse;
};
};
ClientsController.$inject = ['$scope','$log' ,'clientFactory'];
angular.module('clientsApp')
.controller('ClientsController', ClientsController);
}());
This is how my view has been designed:
<h2>Clients</h2>
Filter: <input type="text" ng-model="clientFilter.name" />
<br /><br />
<table>
<tr>
<th ng-click="doSort(name)">Name</th>
<th ng-click="doSort(city)">City</th>
<th ng-click="doSort(joined)">Joined</th>
<th> </th>
</tr>
<tr ng-repeat="cli in clients | filter:clientFilter | orderBy:sortBy:reverse">
<td>{{ cli.name }}</td>
<td>{{ cli.city }}</td>
<td><a href="#/orders/{{ cli.employeeid }}">View Orders</a></td>
</tr>
</table>
<br />
<span>Total clients: {{ clients.length }} </span>
Now, if we look at adding an order total column, here's what I think could be the right approach:
clientFactory.getClients()
.success(function(clients) {
for(var i = 0; i < clients.length; i++) {
var currentClient = clients[i];
var clientOrderTotal = 0;
if (currentClient.orders) {
for (var j = 0; j < currentClient.orders.length; j++) {
clientOrderTotal += parseFloat(currentClient.orders[j].total);
}
} else {
clientOrderTotal = 0;
}
clients[i].orderTotal = clientOrderTotal;
console.log(currentClient.lastname+ " total: " + clientOrderTotal);
}
// After the execution of this logic, update your $scope's clients object.
$scope.clients = clients;
})