ng-repeat - count within html loop

前端 未结 4 1438
后悔当初
后悔当初 2021-01-02 20:04

Is there anyway to count an item, then display it outside of the loop?


   value.total


        
相关标签:
4条回答
  • 2021-01-02 20:39

    Although they do seem to be similar ngRepeat does not work like a for loop in an imperative programming language. The ngRepeat directive consists of two steps that run seperately. First, it produces an array / a map with the repeatet values. Secondly, it renders the template (the elements inside the element with ngRepeat) for each repeatet value. It does not however iterate over a code block like an imperative programming language.

    Even though you may achieve what you try to do with $parent.total, you may run into other pitfalls with this solution as soon as the contents of your array change. To cut it short, you should rather find another way to sum up the values in the array.

    In my opinion, the best place to sum up the values is the controller with a line like this:

    $scope.total = values.reduce(function (a,b) {return a+b});
    
    0 讨论(0)
  • 2021-01-02 20:42

    You can make use of $parent notation to access a $scope variable (from outside ng-repeat) in the ng-repeat scope. So now after initializing it will calculate the total and store it in the $scope variable which was initialized outside.

    Code:

    <div ng-app ng-controller="test">
        <table ng-init="total=0;">
            <tr ng-repeat="value in values">
                <td ng-init="$parent.total = total + value">{{value}}</td>
            </tr>
            <tr>
                <td>Total Of All Values: {{ total }}</td>
            </tr>
        </table>
    </div>
    

    Working Fiddle

    0 讨论(0)
  • 2021-01-02 20:53

    You could always do this in your JS function.

            $scope.values = data;
            angular.forEach($scope.values,function(value){
              $scope.total += value.value;
            });
    

    Working plunker: http://plnkr.co/edit/5WZ9alCXzq115wi3xl4B?p=preview

    0 讨论(0)
  • 2021-01-02 20:59

    total which is initialized in ng-repeat will be of a different scope and can not be accessed outside the loop.

    Try this:

    <table ng-init="total = 0">
    <tr ng-repeat="value in values">
       <td ng-init="$parent.total = $parent.total + value.total">{{value.total}}</td>
    </tr>
    <tr>
       <td>Total Of All Values: {{ total }}</td>
    </tr>
    </table>
    
    0 讨论(0)
提交回复
热议问题