通过几个ng模型迭代

时间:2014-06-23 08:06:31

标签: javascript angularjs

我有一组ng-model元素,并希望将所有值相加并显示它。我的设置看起来像这些

<div ng-app>
  <div ng-controller="SumApp" >
    <input ng-model='val1' type='number' ng-change='calculate()' ng-init='val1=0'/>
    <input ng-model='val2' type='number' ng-change='calculate()' ng-init='val2=0'/> 
    <input ng-model='val3' type='number' ng-change='calculate()' ng-init='val3=0'/>
    <input ng-model='val4' type='number' ng-change='calculate()' ng-init='val4=0'/>
    <div>{{sum}}</div>
  </div>
</div>

我的控制器看起来像这些

<script type="text/javascript">
function SumApp($scope) {
  $scope.sum = 0;

  $scope.calculate = function() {
     $scope.sum = $scope.val1+$scope.val2+$scope.val3+$scope.val4
  };
}
</script>

因此models html 动态生成

问题是,是否有任何方法可以迭代一组元素ng-model 而不在控制器定义中使用任何list

1 个答案:

答案 0 :(得分:1)

随时了解确切的输入数量,您可以轻松使用循环来总结它们:

$scope.sum = 0;
$scope.numInputs = 5;

$scope.calculate = function() {
    var i;
    $scope.sum = 0;

    for(i = 0; i < $scope.numInputs; i++) {
        $scope.sum += parseInt($scope['val' + i], 10);
    }
};