1

Learning angularjs, I am creating a table and when a row creates a new input field creates so you can place a number within and it will do some calculations, but when I update that field it does nothing. I tested it and the input field being outside of the table it works like it should, so what is causing the input field to not respond when it is inside the td tags?

Here is my code: HTML

<h3>ng-repeat example</h3>

<div ng-app="myApp" ng-controller="myCtrl">
   <label>Data Total:</label>
   <input type="number">
   <label>Amount:</label>
   <input type="number" id="total" ng-model="total" ng-change="upateEntries()">
   <label for="input_nr">Users:</label>
    <input type="number" ng-model="entries" ng-change="upateEntries()" class="form-control" id="input_nr" min="0" step="1" value="0">
    </br>

    <table>
       <tr>
          <th>Users</th>
          <th>User Data Total</th>
          <th>Cost</th>
       </tr>
       <tr ng-repeat="item in items track by $index">   
          <td>{{item}}</td>
          <td><input type="number" ng-model="userData" ng-change="updateData()"></td>
          <td>{{amts}}</td>
          <td>{{costs}}</td>
       </tr>
    </table>
</div>

JS

var app = angular.module('myApp',[]);
app.controller('myCtrl', function($scope){
    $scope.total = 0; 
    $scope.entries = 0;
    $scope.userData = 0;
    $scope.items = [];
    $scope.upateEntries = function () {
        $scope.items = [];
        for (var i = 0; i < $scope.entries; i++) {
           $scope.items.push(i + 1);
           $scope.amts = ($scope.total / $scope.entries);
        }
    }

    $scope.updateData = function(){
       $scope.costs = $scope.userData * $scope.total;
    }
});

Link to a pen to play with: https://codepen.io/beartato327/pen/jpQywv

Thanks in advance for the help.

dhilt
  • 18,707
  • 8
  • 70
  • 85
Beartato327
  • 97
  • 2
  • 6
  • New AngularJS developers often do not realize that `ng-repeat`, `ng-switch`, `ng-view`, `ng-include` and `ng-if` all create new child scopes, so the problem often shows up when these directives are involved. – georgeawg Aug 08 '18 at 23:04

1 Answers1

1

The updateData function is definitely called on your input(s) change. The problem is that $scope.userData is always 0. Looks like userData scope conflicts with ng-repeat/item scope. Wrapping userData with a simple object solves the issue:

$scope.container = {
   userData: 0
};
$scope.updateData = function(){
   $scope.costs = $scope.container.userData * $scope.total;
}

And

<tr ng-repeat="item in items track by $index">
   <td><input type="number" ng-model="container.userData" ng-change="updateData()"></td>
   <td>{{costs}}</td>
</tr>
dhilt
  • 18,707
  • 8
  • 70
  • 85