user2708073
user2708073

Reputation: 169

How to return total to <td> tag angular JS from controller

I need to return a total IR for each table cell. This is not working And I am not sure why. How

 $scope.getTotalb = function () {
        var totalb = 0;

        for (var i = 0; i < $scope.items.length; i++) {
            if (120 > $scope.items[i].product && $scope.items[i].product> 90) {
                var product = $scope.items[i].IR;
                totalb += ($scope.items[i].IR);
            }
            return totalb;
        }
    }
    $scope.getTotalc = function () {
        var totalc = 0;

        for (var i = 0; i < $scope.items.length; i++) {
            if (90 > $scope.items[i].product&& $scope.items[i].product> 60) {
                var product = $scope.items[i].IR;
                totalc += ($scope.items[i].IR);
            }
            return totalc;
        }
    }

For Each table data cell, call the function to get total.

<td><b>Total:</b></td>
            <td><b>{{Totala()}}</b></td>
            <td><b></b>{{Totalb()}}</td>

Upvotes: 0

Views: 57

Answers (3)

lanlau
lanlau

Reputation: 21

remove the "return ...." from your 2 "for" loops and make your totals available through the scope.

$scope.getTotalb = function () {
    var totalb = 0;

    for (var i = 0; i < $scope.items.length; i++) {
        if (120 > $scope.items[i].product && $scope.items[i].product> 90) {
            var product = $scope.items[i].IR;
            totalb += ($scope.items[i].IR);
        }

    }
     $scope.totalb=totalb ;

}
$scope.getTotalc = function () {
    var totalc = 0;

    for (var i = 0; i < $scope.items.length; i++) {
        if (90 > $scope.items[i].product&& $scope.items[i].product> 60) {
            var product = $scope.items[i].IR;
            totalc += ($scope.items[i].IR);
        }

    }
    $scope.totalc=totalc ;
}

Upvotes: 0

GStaes
GStaes

Reputation: 328

There are multiple errors in your code.

First, you should put the return statement at the end of your function instead of within your for loop.

Second, the names of the functions are different in your template. In your controller you use getTotalb but in the template you use Totalb.

Upvotes: 1

Vikram Singh
Vikram Singh

Reputation: 972

You should put your return statement outside of for loop

Upvotes: 1

Related Questions