AngularJS:输入值的总和 [英] AngularJS: Sum of Input values

查看:27
本文介绍了AngularJS:输入值的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

HTML

<div ng-repeat="项目中的项目"><p><input type=text value="{{item}}"></p>

总计:<input type=text value="{{sum(items)}}">

脚本

app.controller('MainCtrl', function($scope) {$scope.items = [1,2,5,7];$scope.sum = 函数(列表){变量总数=0;angular.forEach(list , function(item){总计+=项目;});总回报;}});

解决方案

检查这个 fiddle 的实现:http://jsfiddle.net/9tsdv/

注意事项:

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

HTML:

<div ng-repeat="项目中的项目"><p><input type=text ng-model="item.value"></p>

总计:<input type=text value="{{sum(items)}}">

控制器代码:

app.controller('MainCtrl', function($scope) {$scope.items = [ { value: 1 }, { value: 2 }, { value: 5}, { value: 7 } ];$scope.sum = 函数(列表){变量总数=0;angular.forEach(list , function(item){总计+= parseInt(item.value);});总回报;}});

I have a simple list of inputs bound to a list of items that display nicely. When I change a value in an input, the sum doesn't update??

Example: 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>

Script

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;
 }

});

解决方案

Check this fiddle for implementation: http://jsfiddle.net/9tsdv/

The points to take note of:

  • Use ng-model directive with your input element to allow two-way binding between the item model and the input element
  • Since ng-repeat creates a child scope and the elements in items array are of primitive type or value type and hence they are copied by value during the first digest cycle and then further any changes made to the input fields are not reflected in the sum because modifications are bound to now present variables in ng-repeat's created child scope. (See other references on scope inheritance for more details)

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>

Controller code:

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;
 }

});

这篇关于AngularJS:输入值的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆