AngularJS:输入值的总和

Ian*_*ink 4 jquery angularjs

我有一个简单的输入列表绑定到一个显示良好的项目列表.当我更改输入中的值时,总和不会更新?

示例:http://plnkr.co/edit/B7tEAsXSFvyLRmJ5xcnJ?p = preview

HTML

<body ng-controller="MainCtrl">
 <div ng-repeat="item in items">
   <p><input type=text value="{{item}}"></p>
 </div>
 Total: <input type=text value="{{sum(items)}}">
</body>
Run Code Online (Sandbox Code Playgroud)

脚本

app.controller('MainCtrl', function($scope) {
  $scope.items = [1,2,5,7];

 $scope.sum = function(list) {
  var total=0;
  angular.forEach(list , function(item){
    total+= item;
  });
  return total;
 }

});
Run Code Online (Sandbox Code Playgroud)

Rob*_*zvi 9

检查这个小提琴是否实现:http://jsfiddle.net/9tsdv/

需要注意的要点:

  • 将ng-model指令与input元素一起使用,以允许项模型和input元素之间的双向绑定
  • 由于ng-repeat创建子范围,而items数组中的元素是原始类型或值类型,因此它们在第一个摘要周期中按值复制,然后对输入字段所做的任何更改都不会反映在总和中,因为现在,修改绑定到ng-repeat创建的子范围中的变量.(有关详细信息,请参阅有关范围继承的其他参考)

HTML:

<body ng-controller="MainCtrl">
 <div ng-repeat="item in items">
   <p><input type=text ng-model="item.value"></p>
 </div>
 Total: <input type=text value="{{sum(items)}}">
</body>
Run Code Online (Sandbox Code Playgroud)

控制器代码:

app.controller('MainCtrl', function($scope) {
  $scope.items = [ { value: 1 }, { value: 2 }, { value: 5}, { value: 7 } ];

 $scope.sum = function(list) {
  var total=0;
  angular.forEach(list , function(item){
    total+= parseInt(item.value);
  });
  return total;
 }

});
Run Code Online (Sandbox Code Playgroud)