IT

AngularJS ng-repeat에서 반복되는 요소의 계산

lottoking 2020. 8. 9. 09:17
반응형

AngularJS ng-repeat에서 반복되는 요소의 계산


아래 펼쳐는 사용하는 쇼핑 카트를 표시합니다 ng-repeat. 배열의 각 요소에 대해 항목 이름, 해당 금액 및 부분합 ( product.price * product.quantity)을 표시합니다.

반복되는 요소의 총 가격을 계산하는 가장 간단한 방법은 무엇입니까?

<table>

    <tr>
        <th>Product</th>
        <th>Quantity</th>
        <th>Price</th>
    </tr>

    <tr ng-repeat="product in cart.products">
        <td>{{product.name}}</td>
        <td>{{product.quantity}}</td>
        <td>{{product.price * product.quantity}} €</td>
    </tr>

    <tr>
        <td></td>
        <td>Total :</td>
        <td></td> <!-- Here is the total value of my cart -->
    </tr>

</table>

템플릿에서

<td>Total: {{ getTotal() }}</td>

컨트롤러에서

$scope.getTotal = function(){
    var total = 0;
    for(var i = 0; i < $scope.cart.products.length; i++){
        var product = $scope.cart.products[i];
        total += (product.price * product.quantity);
    }
    return total;
}

이 또한 필터와 일반 목록 모두에서 작동합니다. 목록의 모든 값의 전체에 대한 새 필터를 만들고 총 수량의 수행에 대한 솔루션을 만드는 첫 번째 작업입니다. 세부 코드에서 피들러 링크를 확인 하십시오 .

angular.module("sampleApp", [])
        .filter('sumOfValue', function () {
        return function (data, key) {        
            if (angular.isUndefined(data) || angular.isUndefined(key))
                return 0;        
            var sum = 0;        
            angular.forEach(data,function(value){
                sum = sum + parseInt(value[key], 10);
            });        
            return sum;
        }
    }).filter('totalSumPriceQty', function () {
        return function (data, key1, key2) {        
            if (angular.isUndefined(data) || angular.isUndefined(key1)  || angular.isUndefined(key2)) 
                return 0;        
            var sum = 0;
            angular.forEach(data,function(value){
                sum = sum + (parseInt(value[key1], 10) * parseInt(value[key2], 10));
            });
            return sum;
        }
    }).controller("sampleController", function ($scope) {
        $scope.items = [
          {"id": 1,"details": "test11","quantity": 2,"price": 100}, 
          {"id": 2,"details": "test12","quantity": 5,"price": 120}, 
          {"id": 3,"details": "test3","quantity": 6,"price": 170}, 
          {"id": 4,"details": "test4","quantity": 8,"price": 70}
        ];
    });


<div ng-app="sampleApp">
  <div ng-controller="sampleController">
    <div class="col-md-12 col-lg-12 col-sm-12 col-xsml-12">
      <label>Search</label>
      <input type="text" class="form-control" ng-model="searchFilter" />
    </div>
    <div class="col-md-12 col-lg-12 col-sm-12 col-xsml-12">
      <div class="col-md-2 col-lg-2 col-sm-2 col-xsml-2">
        <h4>Id</h4>

      </div>
      <div class="col-md-4 col-lg-4 col-sm-4 col-xsml-4">
        <h4>Details</h4>

      </div>
      <div class="col-md-2 col-lg-2 col-sm-2 col-xsml-2 text-right">
        <h4>Quantity</h4>

      </div>
      <div class="col-md-2 col-lg-2 col-sm-2 col-xsml-2 text-right">
        <h4>Price</h4>

      </div>
      <div class="col-md-2 col-lg-2 col-sm-2 col-xsml-2 text-right">
        <h4>Total</h4>

      </div>
      <div ng-repeat="item in resultValue=(items | filter:{'details':searchFilter})">
        <div class="col-md-2 col-lg-2 col-sm-2 col-xsml-2">{{item.id}}</div>
        <div class="col-md-4 col-lg-4 col-sm-4 col-xsml-4">{{item.details}}</div>
        <div class="col-md-2 col-lg-2 col-sm-2 col-xsml-2 text-right">{{item.quantity}}</div>
        <div class="col-md-2 col-lg-2 col-sm-2 col-xsml-2 text-right">{{item.price}}</div>
        <div class="col-md-2 col-lg-2 col-sm-2 col-xsml-2 text-right">{{item.quantity * item.price}}</div>
      </div>
      <div colspan='3' class="col-md-8 col-lg-8 col-sm-8 col-xsml-8 text-right">
        <h4>{{resultValue | sumOfValue:'quantity'}}</h4>

      </div>
      <div class="col-md-2 col-lg-2 col-sm-2 col-xsml-2 text-right">
        <h4>{{resultValue | sumOfValue:'price'}}</h4>

      </div>
      <div class="col-md-2 col-lg-2 col-sm-2 col-xsml-2 text-right">
        <h4>{{resultValue | totalSumPriceQty:'quantity':'price'}}</h4>

      </div>
    </div>
  </div>
</div>

Fiddle 링크 확인


오래 전에 제시했지만 접근 방식을 게시하고 싶었습니다.

ng-init전체를 계산하는 데 사용 합니다. 이렇게하면 HTML에서 반복하고 컨트롤러에서 할 필요가 없습니다. 이 시나리오에서는 더 깨끗하고 단순한 솔루션이라고 생각합니다. (계산 논리가 더 복잡한 경우 논리를 입력하게 또는 서비스로 이동하는 것이 좋습니다.)

    <tr>
        <th>Product</th>
        <th>Quantity</th>
        <th>Price</th>
    </tr>

    <tr ng-repeat="product in cart.products">
        <td>{{product.name}}</td>
        <td>{{product.quantity}}</td>
        <td ng-init="itemTotal = product.price * product.quantity; controller.Total = controller.Total + itemTotal">{{itemTotal}} €</td>
    </tr>

    <tr>
        <td></td>
        <td>Total :</td>
        <td>{{ controller.Total }}</td> // Here is the total value of my cart
    </tr>

물론 컨트롤러에서 필드 를 정의 / 초기화 하면 됩니다.Total

// random controller snippet
function yourController($scope..., blah) {
    var vm = this;
    vm.Total = 0;
}

ng-repeat다음과 같이 총계를 계산할 수 있습니다 .

<tbody ng-init="total = 0">
  <tr ng-repeat="product in products">
    <td>{{ product.name }}</td>
    <td>{{ product.quantity }}</td>
    <td ng-init="$parent.total = $parent.total + (product.price * product.quantity)">${{ product.price * product.quantity }}</td>
  </tr>
  <tr>
    <td>Total</td>
    <td></td>
    <td>${{ total }}</td>
  </tr>
</tbody>

결과 확인 : http://plnkr.co/edit/Gb8XiCf2RWiozFI3xWzp?p=preview

자동 업데이트 결과 : http://plnkr.co/edit/QSxYbgjDjkuSH2s5JBPf?p=preview (감사합니다 – VicJordan)


이것은 내 해결책입니다

달콤하고 간단한 맞춤 필터 :

(그러나 전체적으로 제품이 아닌 단순한 값과 관련이 있으므로 sumProduct필터를 구성 하고이 게시물에 편집 추가했습니다).

angular.module('myApp', [])

    .filter('total', function () {
        return function (input, property) {
            var i = input instanceof Array ? input.length : 0;
// if property is not defined, returns length of array
// if array has zero length or if it is not an array, return zero
            if (typeof property === 'undefined' || i === 0) {
                return i;
// test if property is number so it can be counted
            } else if (isNaN(input[0][property])) {
                throw 'filter total can count only numeric values';
// finaly, do the counting and return total
            } else {
                var total = 0;
                while (i--)
                    total += input[i][property];
                return total;
            }
        };
    })

JS 바이올린

편집 : sumProduct

이것은 sumProduct필터이며 여러 인수를 허용합니다. 인수로 입력 데이터에서 속성의 이름을 받아들이고 중첩 된 속성 (점으로 중첩 된 속성 :)을 처리 할 수 ​​있습니다 property.nested.

  • 0 인수를 전달하면 입력 데이터의 길이가 반환됩니다.
  • 하나의 인수 만 전달하면 해당 속성 값의 단순하게 반환됩니다.
  • 더 많은 인수를 전달하면 전달 된 속성 값의 곱의 합 (속성의 스칼라)이 반환됩니다.

여기에 JS Fiddle과 코드가 있습니다.

angular.module('myApp', [])
    .filter('sumProduct', function() {
        return function (input) {
            var i = input instanceof Array ? input.length : 0;
            var a = arguments.length;
            if (a === 1 || i === 0)
                return i;

            var keys = [];
            while (a-- > 1) {
                var key = arguments[a].split('.');
                var property = getNestedPropertyByKey(input[0], key);
                if (isNaN(property))
                    throw 'filter sumProduct can count only numeric values';
                keys.push(key);
            }

            var total = 0;
            while (i--) {
                var product = 1;
                for (var k = 0; k < keys.length; k++)
                    product *= getNestedPropertyByKey(input[i], keys[k]);
                total += product;
            }
            return total;

            function getNestedPropertyByKey(data, key) {
                for (var j = 0; j < key.length; j++)
                    data = data[key[j]];
                return data;
            }
        }
    })

JS 바이올린


간단한 솔루션

여기에 간단한 해결책이 있습니다. 루프가 필요하지 않습니다.

HTML 부분

         <table ng-init="ResetTotalAmt()">
                <tr>
                    <th>Product</th>
                    <th>Quantity</th>
                    <th>Price</th>
                </tr>

                <tr ng-repeat="product in cart.products">
                    <td ng-init="CalculateSum(product)">{{product.name}}</td>
                    <td>{{product.quantity}}</td>
                    <td>{{product.price * product.quantity}} €</td>
                </tr>

                <tr>
                    <td></td>
                    <td>Total :</td>
                    <td>{{cart.TotalAmt}}</td> // Here is the total value of my cart
                </tr>

           </table>

펼쳐진 부분

 $scope.cart.TotalAmt = 0;
 $scope.CalculateSum= function (product) {
   $scope.cart.TotalAmt += (product.price * product.quantity);
 }
//It is enough to Write code $scope.cart.TotalAmt =0; in the function where the cart.products get allocated value. 
$scope.ResetTotalAmt = function (product) {
   $scope.cart.TotalAmt =0;
 }

해결하는 또이를 다른 방법은 이 특정 계산을 해결하기위한 바츨라프의 답변 에서 확장됩니다. 즉, 각 행에 대한 계산입니다.

    .filter('total', function () {
        return function (input, property) {
            var i = input instanceof Array ? input.length : 0;
            if (typeof property === 'undefined' || i === 0) {
                return i;
            } else if (typeof property === 'function') {
                var total = 0; 
                while (i--)
                    total += property(input[i]);
                return total;
            } else if (isNaN(input[0][property])) {
                throw 'filter total can count only numeric values';
            } else {
                var total = 0;
                while (i--)
                    total += input[i][property];
                return total;
            }
        };
    })

계산을 통해이를 수행 비용 계산 함수를 범위에 추가하기 만하면됩니다.

$scope.calcItemTotal = function(v) { return v.price*v.quantity; };

{{ datas|total:calcItemTotal|currency }}HTML 코드에서 사용 합니다. 필터를 사용하고 단순하거나 복잡한 다이제스트에 사용할 수 있기 때문에 모든 것이 있습니다.

JSFiddle


이 모든 값을 가지고 item.total 속성으로 모델을 확장하기 위해 ng-repeat 및 ng-init 로이를 수행하는 간단한 방법입니다.

<table>
<tr ng-repeat="item in items" ng-init="setTotals(item)">
                    <td>{{item.name}}</td>
                    <td>{{item.quantity}}</td>
                    <td>{{item.unitCost | number:2}}</td>
                    <td>{{item.total | number:2}}</td>
</tr>
<tr class="bg-warning">
                    <td>Totals</td>
                    <td>{{invoiceCount}}</td>
                    <td></td>                    
                    <td>{{invoiceTotal | number:2}}</td>
                </tr>
</table>

ngInit 지시어는 각 항목에 set total 함수를 호출합니다. 컨트롤러의 setTotals 함수는 각 항목을 계산합니다. 또한 invoiceCount 및 invoiceTotal 범위 변수를 사용하여 모든 항목의 수량과 송장을 (합계)합니다.

$scope.setTotals = function(item){
        if (item){
            item.total = item.quantity * item.unitCost;
            $scope.invoiceCount += item.quantity;
            $scope.invoiceTotal += item.total;
        }
    }

자세한 정보 및 데모는 다음 링크를 참조하십시오.

http://www.ozkary.com/2015/06/angularjs-calculate-totals-using.html


데이터 세트 배열과 각 객체의 키를 합산하는 사용자 지정 Angular 필터를 사용할 수 있습니다. 그럼 필터는 반환 할 수 있습니다.

.filter('sumColumn', function(){
        return function(dataSet, columnToSum){
            let sum = 0;

            for(let i = 0; i < dataSet.length; i++){
                sum += parseFloat(dataSet[i][columnToSum]) || 0;
            }

            return sum;
        };
    })

그런 다음 테이블에서 열을 합산하여 사용할 수 있습니다.

<th>{{ dataSet | sumColumn: 'keyInObjectToSum' }}</th>

나는 우아한 솔루션을 선호한다

템플릿에서

<td>Total: {{ totalSum }}</td>

컨트롤러에서

$scope.totalSum = Object.keys(cart.products).map(function(k){
    return +cart.products[k].price;
}).reduce(function(a,b){ return a + b },0);

ES2015 (일명 ES6)를 사용하는 경우

$scope.totalSum = Object.keys(cart.products)
  .map(k => +cart.products[k].price)
  .reduce((a, b) => a + b);

angular js의 서비스를 사용해 볼 수 있고 저에게 딱 맞습니다. 아래 코드 스 니펫을 제공합니다.

컨트롤러 코드 :

$scope.total = 0;
var aCart = new CartService();

$scope.addItemToCart = function (product) {
    aCart.addCartTotal(product.Price);
};

$scope.showCart = function () {    
    $scope.total = aCart.getCartTotal();
};

서비스 코드 :

app.service("CartService", function () {

    Total = [];
    Total.length = 0;

    return function () {

        this.addCartTotal = function (inTotal) {
            Total.push( inTotal);
        }

        this.getCartTotal = function () {
            var sum = 0;
            for (var i = 0; i < Total.length; i++) {
                sum += parseInt(Total[i], 10); 
            }
            return sum;
        }
    };
});

이 문제에 대한 내 해결책은 다음과 다양합니다.

<td>Total: {{ calculateTotal() }}</td>

펼쳐

$scope.calculateVAT = function () {
    return $scope.cart.products.reduce((accumulator, currentValue) => accumulator + (currentValue.price * currentValue.quantity), 0);
};

감소는 제품 배열의 각 제품에 대해 실행됩니다. Accumulator는 총 누적 금액이고 currentValue는 배열의 현재 요소이며 마지막 0은 초기 값입니다.


RajaShilpa의 답변에 대해 약간 확장했습니다. 다음과 같은 구문을 사용할 수 있습니다.

{{object | sumOfTwoValues:'quantity':'products.productWeight'}}

개체의 마이너스 개체에 액세스 할 수 있습니다. 다음은 필터 코드입니다.

.filter('sumOfTwoValues', function () {
    return function (data, key1, key2) {
        if (typeof (data) === 'undefined' || typeof (key1) === 'undefined' || typeof (key2) === 'undefined') {
            return 0;
        }
        var keyObjects1 = key1.split('.');
        var keyObjects2 = key2.split('.');
        var sum = 0;
        for (i = 0; i < data.length; i++) {
            var value1 = data[i];
            var value2 = data[i];
            for (j = 0; j < keyObjects1.length; j++) {
                value1 = value1[keyObjects1[j]];
            }
            for (k = 0; k < keyObjects2.length; k++) {
                value2 = value2[keyObjects2[k]];
            }
            sum = sum + (value1 * value2);
        }
        return sum;
    }
});

Vaclav의 대답을 취하고 더 Angular와 대화하게 만듭니다.

angular.module('myApp').filter('total', ['$parse', function ($parse) {
    return function (input, property) {
        var i = input instanceof Array ? input.length : 0,
            p = $parse(property);

        if (typeof property === 'undefined' || i === 0) {
            return i;
        } else if (isNaN(p(input[0]))) {
            throw 'filter total can count only numeric values';
        } else {
            var total = 0;
            while (i--)
                total += p(input[i]);
            return total;
        }
    };
}]);

이렇게하면 중첩 및 배열 데이터에도 액세스 할 수있는 이점이 있습니다.

{{data | total:'values[0].value'}}

HTML에서

<b class="text-primary">Total Amount: ${{ data.allTicketsTotalPrice() }}</b>

자바 펼쳐

  app.controller('myController', function ($http) {
            var vm = this;          
            vm.allTicketsTotalPrice = function () {
                var totalPrice = 0;
                angular.forEach(vm.ticketTotalPrice, function (value, key) {
                    totalPrice += parseFloat(value);
                });
                return totalPrice.toFixed(2);
            };
        });

Huy Nguyen의 대답이 거의 다 왔습니다. 작동 광고 다음을 추가하십시오.

ng-repeat="_ in [ products ]"

... ng-init를 사용하여 줄에. 목록에는 항상 단일 항목이 있으므로 Angular는 블록을 정확히 한 번 반복합니다.

필터링을 사용하는 Zybnek의 데모는 다음을 추가하여 작동시킬 수 있습니다.

ng-repeat="_ in [ [ products, search ] ]"

http://plnkr.co/edit/dLSntiy8EyahZ0upDpgy?p=preview를 참조 하십시오 .


**Angular 6: Grand Total**       
 **<h2 align="center">Usage Details Of {{profile$.firstName}}</h2>
        <table align ="center">
          <tr>
            <th>Call Usage</th>
            <th>Data Usage</th>
            <th>SMS Usage</th>
            <th>Total Bill</th>
          </tr>
          <tr>
          <tr *ngFor="let user of bills$">
            <td>{{ user.callUsage}}</td>
            <td>{{ user.dataUsage }}</td>
            <td>{{ user.smsUsage }}</td>
       <td>{{user.callUsage *2 + user.dataUsage *1 + user.smsUsage *1}}</td>
          </tr>


          <tr>
            <th> </th>
            <th>Grand Total</th>
            <th></th>
            <td>{{total( bills$)}}</td>
          </tr>
        </table>**


    **Controller:**
        total(bills) {
            var total = 0;
            bills.forEach(element => {
total = total + (element.callUsage * 2 + element.dataUsage * 1 + element.smsUsage * 1);
            });
            return total;
        }

여기에서 모든 답변을 읽은 후 그룹화 된 정보를 요약하는 방법을 모두 건너 뛰고 SQL 자바 펼쳐 라이브러리 중 하나를로드했습니다. 저는 alasql을 사용하고 있습니다. 예,로드 시간이 몇 초 더 걸리지 만 코딩과 필요에 많은 시간이 절약됩니다. 이제 그룹화하고 () 만 사용합니다.

$scope.bySchool = alasql('SELECT School, SUM(Cost) AS Cost from ? GROUP BY School',[restResults]);

나는 angular / js에 대해 약간의 호언을하는 것처럼 들리지만 실제로 SQL은 30 년 이상을 처리하고 우리는 브라우저 내에서 그것을 다시 발명 할 필요가 없습니다.

참고 URL : https://stackoverflow.com/questions/22731145/calculating-sum-of-repeated-elements-in-angularjs-ng-repeat

반응형