Search code examples
angularjsdynamicform

Sum of Dynamic fields in Anglurjs


Hi I have a dynamic fields like this

<tr ng-repeat="category in staff_categories">
   <td>{{ category.name }}</td>
   <td><input type="text" ng-model="category.permanent"></td>
   <td><input type="text" ng-model="category.temp"></td>
</tr>

It is working fine as expected. It iterate according to staff_categories. Now I want the grand total of category.permanent and category.temp value entered by user and put it in the textbox. Please help

Total permanent:<input type="text">
Total Temp:<input type="text">

Solution

  • Make a function in the controller that will be called and update a scope variable containing total of these values.

    <tr ng-repeat="category in staff_categories">
       <td>{{ category.name }}</td>
       <td><input type="text" ng-model="category.permanent" ng-change="updatePermanentTotal()"></td>
       <td><input type="text" ng-model="category.temp" ng-change="updateTemp()"></td>
    </tr>
    

    Controller Code

    $scope.permanentTotal = 0.0;
    $scope.tempTotal = 0.0;
    
    $scope.updatePermanentTotal = function(){
      $scope.permanentTotal = 0.0;
    
      angular.forEach($scope.staff_categories, function(value, key){
        if(!isNaN(parseInt(value.temp)){
           $scope.tempTotal = $scope.tempTotal + parseInt(value.temp);
          }
        })
    }
    
    $scope.updateTemp = function(){
          $scope.tempTotal = 0.0;
    
          angular.forEach($scope.staff_categories, function(value, key){
            $scope.tempTotal = $scope.tempTotal + parseInt(value.temp);
           })
        }
    

    And bind those two total variables to two inputs like this.

    Total permanent:<input type="text" ng-model="permanentTotal">
    Total Temp:<input type="text" ng-model="tempTotal">