sanu sanu - 4 months ago 50
AngularJS Question

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.



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.


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;