Triven
Triven

Reputation: 351

how to sum inside controller in angularjs

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

Upvotes: 0

Views: 731

Answers (2)

Brocco
Brocco

Reputation: 64843

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.

Upvotes: 1

Lajos Veres
Lajos Veres

Reputation: 13725

You should force somehow numbers, and bind the details:

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

Upvotes: 1

Related Questions