Как суммировать все значения массива, используя Angular

0

Я создаю динамический список форм, а в строке есть промежуточная величина, и мне нужно иметь общую сумму. Но моя проблема в том, что я не могу суммировать все значения.

Вот немного моего кода:

//i created a array that will hold all subtotals
$scope.grand_total = [];

//this function is visible in every row
$scope.subTotal = function($index) {

    var total = 0;

    angular.forEach($scope.quoteHeader.items[$index], function(value){

        angular.forEach(value.items, function(v) {

            total += v.unit * v.unit_price;

            $scope.grand_total.push({
                subtotal: total
            });

        });

    });

    return total;

}

//this will process the sum but It didn't work
function computeGrandTotal() {

    var total = 0;

    angular.forEach($scope.grand_total, function(value) {
        console.log(value);
    });

}

$scope.grandTotal = function() {

    var total = 0.00;

    computeGrandTotal(); //call the subtotal function

    console.log(computeGrandTotal());

    return total;

}

Здесь plnkr: http://plnkr.co/edit/Bfd1e5?p=preview

Надеюсь, ты сможешь мне помочь. Спасибо, достаточно :)

Теги:

1 ответ

1
Лучший ответ

Вам нужно сохранить общее значение по данному индексу в массиве sub_total, затем

	var quotationList = angular.module('quotation_list', []);

	quotationList.controller('quoteList', function($scope) {

	  $scope.quoteHeader = {};

	  $scope.quoteHeader = {
	    items: []
	  }

	  $scope.json_output = angular.fromJson($scope.quoteHeader); //display json view

	  $scope.addParticularHeader = function() {

	    $scope.quoteHeader.items.push({
	      particular_name: 'SAMPLE PARTICULAR TITLE',
	      child_label: {
	        items: []
	      }
	    });

	  }

	  $scope.removeQuoteHeader = function($index) {
	    $scope.quoteHeader.items.splice($index, 1);
	  }

	  $scope.addParent = function($index) {

	    //here we will append the new row
	    //console.log($scope.quoteHeader.items[$index].child_label);

	    $scope.quoteHeader.items[$index].child_label.items.push({
	      particular: 'Sample Particular Name',
	      unit: 1,
	      unit_label: 'sqm',
	      unit_price: 0.00,
	      unit_subtotal: 0.00,
	      sublevel: {
	        items: []
	      }
	    });

	  }

	  $scope.removeParent = function(parent_id, $index) {
	    $scope.quoteHeader.items[parent_id].child_label.items.splice($index, 1);
	  }

	  $scope.addSubLevel = function(parent_id) {

	    console.log(parent_id);

	  }

	  $scope.grand_total = [];

	  $scope.subTotal = function($index) {

	    var total = 0;

	    angular.forEach($scope.quoteHeader.items[$index], function(value) {

	      angular.forEach(value.items, function(v) {
	        total += v.unit * v.unit_price;
	      });

	    });
	    $scope.grand_total[$index] = total;

	    return total;

	  }

	  function computeGrandTotal() {

	    var total = 0;

	    //console.log($scope.grand_total);

	    angular.forEach($scope.grand_total, function(value) {
	      console.log('total', value);
	      total += value;
	    });

	    return total;
	  }

	  $scope.grandTotal = function() {
	    return computeGrandTotal();

	  }

	});
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet" />
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" />
<script src="//code.angularjs.org/1.3.16/angular.js"></script>
<div class="container">
  <h1>Quotation List</h1>
  <div ng-app="quotation_list" class="row">
    <div ng-controller="quoteList">
      <div class="row">
        <div class="col-md-12 text-right">
          <button ng-click="addParticularHeader()" class="btn btn-primary" type="button">
            <span class="fa fa-plus"></span>
            Add Particular Header</button>
        </div>
      </div>
      <hr />
      <div class="row" ng-repeat="item in quoteHeader.items">
        <div class="panel panel-default">
          <div class="panel-heading">
            <h5 contenteditable="" class="panel-title">{{ item.particular_name }} - {{ $index + 1}}                <span ng-click="removeQuoteHeader($index)" class="pull-right btn btn-danger">
              <span class="fa fa-times"></span>
              Remove</span>
            </h5>
            <div class="clearfix"></div>
          </div>
          <div class="panel-body">
            <div class="table-responsive">
              <table class="table table-bordered">
                <thead>
                  <tr>
                    <td class="text-center">No.</td>
                    <td class="text-center">Particulars</td>
                    <td class="text-center">Unit</td>
                    <td class="text-center">Unit Label</td>
                    <td class="text-center">Unit(Price)</td>
                    <td class="text-center">Unit Price(Php)</td>
                    <td class="text-center"></td>
                  </tr>
                </thead>
                <tbody>
                  <tr ng-repeat="item in quoteHeader.items[$index].child_label.items">
                    <td class="text-center">{{ $index + 1 }}</td>
                    <td class="text-center">
                      <input type="text" ng-model="item.particular" class="form-control" />
                    </td>
                    <td class="text-center">
                      <input type="number" ng-minlength="1" ng-model="item.unit" class="form-control text-center" />
                    </td>
                    <td class="text-center">
                      <select class="form-control">
                        <option value="sqm">sqm</option>
                        <option value="lot">lot</option>
                        <option value="sets">sets</option>
                      </select>
                    </td>
                    <td class="text-center">
                      <input type="number" ng-model="item.unit_price" class="form-control text-right" />
                    </td>
                    <td class="text-center">
                      <input type="text" readonly="" value="{{ item.unit * item.unit_price | currency: '₱ ' }}" class="form-control text-right" />
                    </td>
                    <td class="text-center">
                      <button ng-click="addSubLevel($parent.$index)" class="btn btn-primary" type="button">
                        <span class="fa fa-plus"></span>
                      </button>
                      <button ng-click="removeParent($parent.$index, $index)" class="btn btn-danger" type="button">
                        <span class="fa fa-times"></span>
                      </button>
                    </td>
                  </tr>
                  <tr>
                    <td ng-show="!quoteHeader.items[$index].child_label.items.length" class="text-center" colspan="7">
                      <p>No list yet!</p>
                    </td>
                  </tr>
                </tbody>
                <tfoot>
                  <tr>
                    <td class="text-center" colspan="6">
                      <button ng-click="addParent($index)" class="btn btn-primary" type="button">
                        <span class="fa fa-plus"></span>Add Parent</button>
                    </td>
                    <td>
                      <label>Subtotal: <span>{{ subTotal($index) | currency: '₱ ' }}</span>
                      </label>
                    </td>
                  </tr>
                </tfoot>
              </table>
            </div>
          </div>
        </div>
      </div>
      <div ng-show="!quoteHeader.items.length" class="row text-center">
        <p>No particulars yet!</p>
      </div>
      <div class="pull-right">
        <label>Grand Total:</label>
        <p>{{ grandTotal() }}</p>
        <!--
<input type="text" class="form-control text-right" value="{{ grandTotal() | currency: '₱ ' }}" readonly />
-->
      </div>
      <div class="clearfix"></div>
    </div>
  </div>
</div>
  • 0
    plnkr.co/edit/YSq8VFSg1aOBYePhRLRu?p=preview
  • 0
    Спасибо за очень хороший ответ. :) Теперь это работает :)

Ещё вопросы

Сообщество Overcoder
Наверх
Меню