Calculate total of rows in ng-repeat with other controller

主宰稳场 提交于 2019-12-13 19:15:15

问题


I got rows where a total will be calculated.

In my ng-repeat I have a controller RowCtrl where I calculate the total.

app.controller('RowCtrl', function ($scope) {
   $scope.unit_price = 0;
   $scope.quantity = 0;

   $scope.$watchCollection('[row.unit_price, row.quantity]', function () {
      $scope.row.total = $scope.row.unit_price * $scope.row.quantity;
   });
});

How can I calculate the total of all the rows?

In the fiddlr I have a demo of the rows where the total of a row is already calculated.

Fiddlr: http://jsfiddle.net/9t9em/1/


回答1:


you don't need RowCtrl

http://jsfiddle.net/9t9em/5/

app.controller('MainCtrl', function ($scope) {
    $scope.rows = [{
        unit_price: 1,
        quantity: 0
    }, {
        unit_price: 2,
        quantity: 0
    }, {
        unit_price: 3,
        quantity: 0
    }];
    $scope.$watch('rows', function () {
        $scope.total = 0
        angular.forEach($scope.rows, function(row){
            $scope.total += row.unit_price * row.quantity
        })
    }, true)
});



回答2:


Yes, it is possible - just use objectEquality parameter(to check child elements for changes):

$scope.$watch('rows', function () {...}, true);

But better - just do it in your template:

{{unit_price * quantity | number:2}}

This would be more efficient, and less error-prone.


Why It should be in view?

Because it is view logic.. I mean: it is about: how to display certain row.

Is it ok to put this logic to view?

In case of simple multiplication(as in this case) - I think, it is OK. But in more complicated cases it would be better to add special filter for this.

Why it would be mach more efficient than deep watch and totals recalculation on it?

Because this recalculations would be called on every possible change in every row, and will recalculate all totals (not olny required one). But if you do this in view - angular would be watching only for certain properties in certain rows, so it will recalculate total only when this would be required.



来源:https://stackoverflow.com/questions/24323446/calculate-total-of-rows-in-ng-repeat-with-other-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!