输入值的角度和,不更新 [英] Angular Sum of Input values, not updating

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

问题描述

我有绑定到显示很好的项目的列表的输入的简单列表。当我在输入更改值,总和不更新??

例如: http://plnkr.co/edit/B7tEAsXSFvyLRmJ5xcnJ?p=preVIEW

HTML

 <机身NG控制器=MainCtrl>
 < D​​IV NG重复=项中的项目>
   < P><输入类型=文本值={{项目}}>< / P>
 < / DIV>
 总计:<输入类型=文本值={{总和(项目)}}>
< /身体GT;

剧本

  app.controller('MainCtrl',函数($范围){
  $ scope.items = [1,2,5,7]; $ scope.sum =功能(名单){
  无功总= 0;
  angular.forEach(列表功能(项目){
    共+ =项目;
  });
  总回报;
 }});


解决方案

勾选此捣鼓实现: http://jsfiddle.net/9tsdv/

中的点要注意的:


  • 使用您的输入元素NG-模型的指令,让项目模型和输入元素
  • 之间的双向绑定
  • 由于NG-重复创建一个子范围和项目数组中的元素是基本类型或值类型的,因此它们被值的第一个消化的周期内复制,然后进一步向输入字段所做的任何更改都不会反映在因为修改绑定的总和,现在美元的NG-repeat的创建子范围p $ psent变量。 (见继承范围更多详细信息,其他的引用)

HTML:

 <机身NG控制器=MainCtrl>
 < D​​IV NG重复=项中的项目>
   < P><输入类型=文本NG模型=item.value>< / P>
 < / DIV>
 总计:<输入类型=文本值={{总和(项目)}}>
< /身体GT;

控制器code:

  app.controller('MainCtrl',函数($范围){
  $ scope.items = [{值:1},{值:2},{值:5},{值:7}]; $ scope.sum =功能(名单){
  无功总= 0;
  angular.forEach(列表功能(项目){
    总+ = 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;
 }

});

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆