sanu
sanu

Reputation: 1068

Angularjs ng-value sum fields

Hi i have inputs like this

<input type="text" ng-model="tbl.Public">
<input type="text" ng-model="tbl.Private">
<input type="text" ng-value="tbl.Public--tbl.Private" ng-model="tbl.Total">

the above form will working fine it will sum the Public and Private value and put it in tbl.Total field. My problem is in edit form where value of tbl.Total, tbl.Public, tbl.Private are assign from database.

js

$scope.tbl.Public=10;
$scope.tbl.Private=25;
$scope.tbl.Total=35;

now after assigning a value from js when i change value of tbl.Public or tbl.Private in form it is not affecting a tbl.Total it should sum the two value and put it in tbl.Total field. Thank you for your any help and suggestion.

Upvotes: 0

Views: 1534

Answers (2)

sanu
sanu

Reputation: 1068

It should be like this to prevent from concatenate

$scope.updateTotal = function() { 
  var Public = Number($scope.tbl.Public || 0); 
  var Private = Number($scope.tbl.Private || 0); 
  $scope.tbl.Total = Public + Private; 
} 

Upvotes: 0

Robin-Hoodie
Robin-Hoodie

Reputation: 4974

ng-value is usually used on radiobuttons and option elements, it's not a good fit for your use case.

A better thing to do would be implementing an updateTotal() function combined with ng-change. I would also recommend changing your input types to number so you're not allowing users to sum text.

<input type="number" ng-model="tbl.Public" ng-change="updateTotal();">
<input type="number" ng-model="tbl.Private" ng-change="updateTotal();">
<input type="number" ng-model="tbl.Total">

In your controller:

$scope.updateTotal = function() {
  $scope.tbl.Total = $scope.tbl.Public + $scope.tbl.Private;
}

Upvotes: 3

Related Questions