动态表单 Angular 问题

Dynamic form Angular issue

我在网上写了这段代码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 bindings中不需要提到$scope,直接引用controller的$scope/this(context)

除此之外,另外将所有输入的 ng-bind 更改为 ng-model 以启用对所有输入字段的双向绑定。

标记

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

Forked JSFiddle

使用

<input type="text" ng-model="item.a">

而不是

<input type="text" ng-bind="item.a">

已更新 fiddle http://jsfiddle.net/Lhkedykz/17/