如何在角度中添加多个模型

时间:2014-08-23 01:21:34

标签: javascript angularjs

我有一些数字输入:

<input class="title form-control" id="quantity1" min="0" name="quantity1" ng-model="option1" type="number" value="0">
<input class="title form-control" id="quantity2" min="0" name="quantity2" ng-model="option2" type="number" value="0">
<input class="title form-control" id="quantity3" min="0" name="quantity3" ng-model="option3" type="number" value="0">
<input class="title form-control" id="quantity4" min="0" name="quantity4" ng-model="option4" type="number" value="0">

在其他数字输入中,我想显示总数量。

<input class="title form-control" id="quantity" min="0" name="quantity" ng-model="quantityTotal" type="number" value="0">

我如何将多个绑定添加到一起。

2 个答案:

答案 0 :(得分:1)

更新:你可以在这里使用控件的value属性。所以它会像:

<input  class="title form-control" id="quantity" min="0" name="quantity" value="{{option1+option2+option3+option4}}" type="number" />

Working Fiddle

答案 1 :(得分:1)

有两种方法可以轻易想到。

首先,您可以使用ng-change来调用函数来更新总数:

HTML:

 <input class="title form-control" id="quantity1" min="0" name="quantity1" ng-change="onQuantityChange()" ng-model="option1" type="number">
 <input class="title form-control" id="quantity2" min="0" name="quantity2" ng-change="onQuantityChange()" ng-model="option2" type="number">
 <input class="title form-control" id="quantity3" min="0" name="quantity3" ng-change="onQuantityChange()" ng-model="option3" type="number">
 <input class="title form-control" id="quantity4" min="0" name="quantity4" ng-change="onQuantityChange()" ng-model="option4" type="number">

 <input class="title form-control" id="quantity" min="0" name="quantity" type="number" ng-model="quantityTotal">

功能:

$scope.onQuantityChange = function() {
    $scope.quantityTotal = $scope.option1 + $scope.option2 + $scope.option3 + $scope.option4;
  };

您也可以只将表达式添加到总输入的值中,如下所示:

<input class="title form-control" id="quantity" min="0" name="quantity" type="number" value="{{opt1+opt2+opt3+opt4}}">

以下是处理plnkr.

的两个解决方案

旁注第一种方法可能是首选方法,因为通常很好的做法是避免将业务逻辑放入标记中。

希望这会有所帮助。干杯!