0

I have created a scope function like this.

$scope.getTotal = function(){
        var total1 = 0;
        var total2 = 0;
        var total3 = 0;
        for(var i = 0; i < $scope.today.length; i++){
            var ordqt = $scope.today[i]["OrdQ"];
            var ordvval = $scope.today[i]["OrdSV"];
            var resqt = $scope.today[i]["RecQ"];

            total1 = +total1 + +ordqt;
            total2 = +total2 + +ordvval;
            total3 = +total3 + +resqt;

        }
        total = total1+"@"+total2+"@"+total3;
        return total;
    }

How can I split the values from the getTotal function to display here?

<td>{{ getTotal() }}<td>
<td>{{ getTotal() }}<td>
<td>{{ getTotal() }}<td>
2
  • 1
    w3schools.com/jsref/jsref_split.asp Commented Sep 3, 2015 at 6:43
  • how would you like to split it ? , you add 3 values and return the result ? Commented Sep 3, 2015 at 6:43

2 Answers 2

4

You should correct below lines

total1 = total1 + ordqt;
total2 = total2 + ordvval;
total3 = total3 + resqt;

You could do it by using ng-repeat.

<td ng-repeat="total in getTotal().split('@') track by $index">
    {{ total }}
</td>
Sign up to request clarification or add additional context in comments.

2 Comments

I which format I need to return the value from getTotal function? @pankaj
@Pravin in a string format as you are doing now..which will have values @ separated
1

You shouldn't join them in the first place:

$scope.getTotal = function() {
    // ...
    return {
        total1: total1,
        total2: total2,
        total3: total3
    };
}

and

<td>{{ getTotal().total1 }}<td>
<td>{{ getTotal().total2 }}<td>
<td>{{ getTotal().total3 }}<td>

Or even better, make 3 different functions, computing the 3 different totals, and call each function from the view.

Or even better, make a single function taking the field you want to compute the total for in argument:

$scope.getTotal = function(field){
    var total = 0;
    for (var i = 0; i < $scope.today.length; i++){
        var value = $scope.today[i][field];
        total = +total + +value;
    }
    return total;
}

and use

<td>{{ getTotal('OrdQ') }}<td>
<td>{{ getTotal('OrdSV') }}<td>
<td>{{ getTotal('RecQ') }}<td>

Note that your code would be much more readable if you used meaningful names. What do OrdQ and ordqt mean? Why use ordqt sometimes and OrdQ sometimes, for the same thing. Why not use something meaningful like, I guess, orderQuantity?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.