javascript - 动态形式Angular问题

标签 javascript angularjs data-binding angular-ngmodel ng-bind

我在网上写了这段代码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)"

Forked JSFiddle

关于javascript - 动态形式Angular问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38570816/

相关文章:

javascript - AngularJS/用户界面路由器 : handle 404 on resolve

javascript - Angular 1.5 通过使用另一个组件返回函数中的 html 结果

c# - Gridview 中的 DataBind 用户控件

javascript - 当内容来自 Ajax 调用时访问 div 内容时出现问题

javascript - window.orientation 报告 onresize 中的旧值

javascript - 如何获得正确的 SVG 代码

wpf - 约什史密斯的传奇文章 : I need a bit more on the DataBinding that takes place

javascript - 如何使用 $scope.$watch 和 ng-repeat?

javascript - AngularJS 中的复杂表单验证

javascript - d3.js 绑定(bind)数组中的数据数组