ng-repeat td中的输入字段不会触发功能

时间:2018-08-08 19:43:57

标签: javascript angularjs angularjs-ng-repeat angular-ngmodel

学习angularjs,我正在创建一个表,当一行创建一个新的输入字段时,会创建一个表,以便您可以在其中放置一个数字并进行一些计算,但是当我更新该字段时,它什么也没做。我测试了它,并且输入字段在表的外部,它应该像它应该的那样工作,那么是什么导致了输入字段在td标签内部时不响应?

这是我的代码: 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;
    }
});

链接到可玩的笔:https://codepen.io/beartato327/pen/jpQywv

预先感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

肯定会在您的输入更改时调用updateData函数。问题是$scope.userData始终为0。看起来userData范围与ng-repeat / item范围冲突。用简单的对象包装userData可解决此问题:

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

<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>