ng-repeat - count within html loop

前端 未结 4 1511
后悔当初
后悔当初 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});
    

提交回复
热议问题