gentos gentos - 4 months ago 33
AngularJS Question

AngularJS sum fields on change update sum

I need to sum 3 inputs and in the 4th to be displayed the result, If i change the result the 3 other sum input should be equal to the result

Initial values:

1 = 100 #2 = 100 #3 = 100 #4 = 300



User interacts with field #1:

1 = 200 #2 = 100 #3 = 100 #4 = 400



User interacts with field #4 after editing #1:

1 = 150 #2 = 75 #3 = 75 #4 = 300



$scope.sum = function(){
return $scope.result = $scope.input1+$scope.input2+$scope.input3;
}


and my algorithm I think is :

on key press : $scope.result /3, and update the other 3 inputs.

thank you

Answer

Your ngModel's are actually strings, first you have to parse them to int and sum.

Here's a simple example:

(function() {
  "use strict";

  angular
    .module('app', [])
    .controller('MainCtrl', MainCtrl);

  MainCtrl.$inject = ['$scope'];

  function MainCtrl($scope) {
    $scope.sum = function() {
      $scope.input4 = parseInt($scope.input1 || 0) + parseInt($scope.input2 || 0) + parseInt($scope.input3 || 0);
    }
    
    $scope.slice = function() {
      $scope.input1 = $scope.input2 = $scope.input3 = $scope.input4 / 3;
    }
  }
})();
<!DOCTYPE html>
<html ng-app="app">

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css" />
</head>

<body ng-controller="MainCtrl">
  <div class="col-md-12">
    <input type="text" ng-model="input1" ng-change="sum()">
    <input type="text" ng-model="input2" ng-change="sum()">
    <input type="text" ng-model="input3" ng-change="sum()">
    <hr>
    Result: <input type="text" ng-model="input4" ng-change="slice()">
  </div>
</body>

</html>