0

I have few inputs and I want to show total in view. I found one solution here

but I wanna know what is the problem in my code. I am trying to sum inside my controller.

HTML:

<body ng-app = 'trivenapp'>
<div ng-controller = 'mycontroller'>
<input ng-model = 'inputvalue1'></input>
<input ng-model = 'inputvalue2'></input>
<input ng-model = 'inputvalue3'></input>
<span>{{total}}</span>
</div>
</body>

Angular:

var myapp = angular.module('trivenapp',[]);
myapp.controller('mycontroller',function($scope){
$scope.total = ($scope.inputvalue1) + ($scope.inputvalue2) + ($scope.inputvalue3);
});

JSBin: JSBin

2 Answers 2

1

Change total to be a function...

$scope.total = function(){
    return (parseInt($scope.inputvalue1) +
           parseInt($scope.inputvalue2) +
           parseInt($scope.inputvalue3)) || 0;
});

and change your binding to:

<span>{{total()}}</span>

The reason your code isn't working is because you're explicitly setting total to a number, which does not automatically update when the other values update.

Sign up to request clarification or add additional context in comments.

4 Comments

To add to this, $scope.inputvalue1, 2, and 3 are strings. If you input 5, 6, and 7, you will total() will be "567." Convert them to integers. See jsBin jsBin
@Tom thanks for pointing out the parsing, I'd just copied the code from the question for simplicity
There is still a little issue. The $scope.total is null at the time of page load and hence I am getting 'null' in view but I want either 0 or blank as default in view . Also I get total only after filling in all boxes . Please suggest
Updated to handle nulls, if any of them are not a number, then it will be 0, but you can change this to handle null for each one individually so that the sum of [1, 'A', 4] would be 5.
1

You should force somehow numbers, and bind the details:

<span>{{1*inputvalue1+1*inputvalue2+1*inputvalue3}}</span>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.