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

Community
  • 1
  • 1
Triven
  • 351
  • 1
  • 4
  • 17

2 Answers2

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.

Brocco
  • 62,737
  • 12
  • 70
  • 76
  • 2
    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](http://jsbin.com/wocezufa/1/) – Tom Apr 01 '14 at 14:54
  • @Tom thanks for pointing out the parsing, I'd just copied the code from the question for simplicity – Brocco Apr 01 '14 at 15:28
  • 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 – Triven Apr 01 '14 at 15:41
  • 1
    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. – Brocco Apr 01 '14 at 15:44
1

You should force somehow numbers, and bind the details:

<span>{{1*inputvalue1+1*inputvalue2+1*inputvalue3}}</span>
Lajos Veres
  • 13,595
  • 7
  • 43
  • 56