如何使用 AngularJS 动态获取文本框值

How to get text box values dynamically using AngularJS

本文关键字:取文本 获取 动态 何使用 AngularJS      更新时间:2023-09-26

我按照以下教程在 Angular 中添加了两个值;在 AngularJS 中添加两个数字

但是现在我必须在ng-repeat中对动态文本框值求和。

我有以下代码

网页代码

 ......
        <table>
            <tr>
                <th>Name</th>
                <th>Days</th>
            </tr>
            <tr ng-repeat="si in serImp">
                <td>{{si.Name}}</td>
                <td><input type="number" ng-model="si.Days" /></td>
            </tr>
        </table>
        .......
        <button ng-click="sum()">Calculate</button>
        .......

JS代码

.........
        $scope.serImp = [];
        $scope.serImp = data;
                // here data is object contain multiple Name+Durations e.g. 
        /*data = 
        [0]
   Name:"first"
   Days: 1
[1]
   Name:"second"
   Days: 2
[2]
   Name:"third"
   Days: 3*/
         $scope.sum = function () {
// sum code goes here
    }
    ........

我的问题是:我怎样才能从 ng-model="si 中获取值/数字的总和。天">

使用 reduce 来总结所有的日子。当您使用 ng-model 修改值时,您正在操作$scope.serImp数组。然后,您可以使用这些值来计算总和。

$scope.sum = function () {
     return $scope.serImp.reduce(function(prv, cur) { 
         return prv.Days + cur.Days; 
     });
}

Reduce采用一个数组,并通过将一个函数应用于其所有元素将其减少到一个值。在我们的例子中,只是简单地将所有的日子加起来。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

我将创建函数,该函数将返回所有天数总计并直接绑定到html

{{totalDays()}}

法典

$scope.totalDays = function(){
  var totalDays = 0;
  angular.forEach( $scope.serImp, function(si){
     if(si.Days && !isNaN(si.Days)){
        totalDays += Number(si.Days);
     }
  })
}