2016-10-12 3 views
0

Я изучаю angularjs (не 2) и пытаюсь выяснить, как рассчитать общую сумму заказа клиента.вычисление данных json в angularjs

мои данные выглядит следующим образом:

var customers = [ 
      { 
       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 
        } 
       ] 
      } 
] 

У меня есть завод, и контроллер, который принимает эти данные и ...

мой контроллер выглядит следующим образом:

(function() { 

    var CustomersController = function ($scope, $log, customerFactory) { 
     $scope.sortBy = 'name'; 
     $scope.reverse = false; 
     $scope.customers = []; 

     function init() { 

      customerFactory.getCustomers() 
       .success(function(customers) { 
        $scope.customers = customers; 

      }) 
      .error(function(data, status, headers, config){ 
       $log.log(data.error + ' ' + status); 

      }); 

     } 

     init(); 

     $scope.doSort = function(propName) { 
      $scope.sortBy = propName; 
      $scope.reverse = !$scope.reverse; 
     }; 


    }; 

    CustomersController.$inject = ['$scope','$log' ,'customerFactory']; 

    angular.module('customersApp') 
     .controller('CustomersController', CustomersController); 

}()); 

мой взгляд выглядит следующим образом:

<h2>Customers</h2> 
Filter: <input type="text" ng-model="customerFilter.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>&nbsp;</th> 
    </tr> 
    <tr ng-repeat="cust in customers | filter:customerFilter | orderBy:sortBy:reverse"> 
     <td>{{ cust.name }}</td> 
     <td>{{ cust.city }}</td> 
     <td><a href="#/orders/{{ cust.employeeid }}">View Orders</a></td> 
    </tr> 
</table> 
<br /> 
<span>Total customers: {{ customers.length }} </span> 

Я понимаю, как добавить в колонку общего порядка ... но как вы ее вычисляете с учетом возвращаемого json?

--------------- EDIT --------------

Я думаю, что это движется в правильном пути?

customerFactory.getCustomers() 
     .success(function(customers) { 
      for(var i = 0; i < customers.length; i++) { 
       var currCustomer = customers[i]; 
       var aCustomerTotal = 0; 

       if (currCustomer.hrs) { 

        for (var j = 0; j < currCustomer.hrs.length; j++) { 
         aCustomerTotal += parseInt(currCustomer.hrs[j].bllhrs); 
        } 
       } else { 
        aCustomerTotal=0 
       } 
       customers[i].orderTotal = aCustomerTotal; 
       console.log(currCustomer.lastname + " total: " + aCustomerTotal); 
      } 
      // after the exeuction of this logic set your $scope's customer to the modified object. 
      $scope.customers = customers; 
     }) 
+0

Вам необходимо перебрать и вычислить в контроллере – charlietfl

+0

также вы должны передать имя свойства 'ng-click =" doSort ('name') "' следовать за тем же для других 'ng-click''s –

+0

@charlietfl I думаю, я понял, что ... это создаст новый элемент в «клиентах»? Будет ли у меня «customer.orderTotal»? – user2061886

ответ

1

Если все, что вы застряли на получает в общей сложности для каждого клиента -> Вы можете использовать простой двойной цикл:

.success(function(customers) { 
    for(var i = 0; i < customers.length; i++) { 
     var currCustomer = customers[i]; 
     var aCustomerTotal = 0; 
     for (var j = 0; j < currCustomer.orders.length; j++) { 
      aCustomerTotal += currCustomer.orders[j].total; 
     } 
     customers[i].orderTotal = aCustomerTotal; 
     console.log(currCustomer.name + " total: " + aCustomerTotal); 
    } 
    // after the exeuction of this logic set your $scope's customer to the modified object. 
    $scope.customers = customers; 
} 
+0

Я вижу, где вы собираетесь с этим ... я помещаю это в контроллер? и если да ... как вы добавляете это к '$ scope.customers = customers;'? – user2061886

+0

Я сделал редактирование с тем, что вы предложили ... но я не понимаю, как добавить результат обратно к исходному объекту json ... извините ... новичок в этом все ... – user2061886

+0

Отредактировал свой ответ, чтобы показать как изменить объект 'customer' с общей суммой клиента, а затем добавить этот измененный объект в область. – httpNick

1

Вы можете создать custom filter для этого (скажем, вы также можете использовать lodash для упрощения):

angular.module('customersApp', []) 
.filter('customerTotal', function() { 
    return function(customer) { 
    return _.reduce(customer.hrs, function(sum, hrs) { 
     return sum + parseInt(hrs.bllhrs); 
    }, 0); 
    }; 
}); 

И вы можете использовать этот фильтр так:

<td>{{ curr.name }} total: {{ cust | customerTotal }}</td>