我在网上写了这段代码dynamic form jsFiddle code
总计和总计不会自动更新。我之前有一个更简单的示例,它使用单个模型项,但后来我创建了一个数组,现在它不起作用。我正在构建的真正程序将具有更多字段,我正在尝试创建一个预示例来表明它可以工作。有人能很快看出我忘记了什么愚蠢的事情吗?
<div ng-controller="MyCtrl">
<form name="myForm">
<div ng-repeat="item in items track by $index">
<input type="text" ng-model="item.a">
<input type="text" ng-model="item.b">
<input type="text" ng-model="item.c">
<label>Total: </label><label ng-bind="total(item)"></label>
</div>
</form>
<div>
<label>Grand Total: </label><label ng-bind="grandTotal()"></label>
</div>
</div>
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', function($scope) {
$scope.items = [
{
a: 0, b: 0, c: 0
},
{
a: 0, b: 0, c: 0
}];
$scope.total = function(item) {
var result = item.a * item.b * item.c;
return isNaN(result) ? 0 : result;
};
$scope.grandTotal = function() {
var result = 0;
angular.forEach($scope.items, function(item) {
result += $scope.total(item);
});
return isNaN(result) ? "" : result.toString();
};
});
最佳答案
ng-bind
应该没有 $scope
。您不需要在 View 绑定(bind)中提及 $scope
,它直接引用 Controller 的 $scope
/this
(context)。
除此之外,还将所有输入的 ng-bind
更改为 ng-model
以启用所有输入字段的双向绑定(bind)。
标记
<input type="text" ng-model="item.a">
<input type="text" ng-model="item.b">
<input type="text" ng-model="item.c">
ng-bind="total(item)"
关于javascript - 动态形式Angular问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38570816/