学习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
预先感谢您的帮助。
答案 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>