AngularJS - 多重绑定 - 计算输入值

问题描述 投票:3回答:1

我正在用AngularJS构建一个大型表单,它将用很多公式和函数替换一个巨大的excel电子表格。简而言之,这个表单是一个计算器 - 其中许多值取决于以前的值。我目前的方法是在所有影响下一个输入的输入上添加ng-change-同时将观察者添加到以编程方式更改的字段中。我发现这种做法非常混乱,难以维护。做这种工作的任何更好的模式?

我正在构建的完整表单包含60多个相互交互的字段。所有计算值,例如“价格”,都需要手动更改或覆盖。因此,下面示例中的“总价”的计算应该是自动的,无论价格是通过先前的值计算还是手动更改。

小例子:

<div ng-app>
  <h2>Calculator</h2>

  <div ng-controller="TestCtrl">
    <form>
        <li>Width (cm): <input type="text" ng-change="changePrice()" ng-model="width"/> </li>
        <li>Height (cm): <input type="text" ng-change="changePrice()" ng-model="height"/> </li>
        <li>Depth (cm)<input type="text" ng-change="changePrice()" ng-model="depth"/>  </li>   
        <li>Price per cm3<input type="text" ng-change="changePrice()" ng-model="priceCm"/>  </li>
        <li><b>Price</b><input type="text" ng-model="price"/>  <br/><br/></li>
        <li>Packaging price<input type="text" ng-change="changeTotalPrice()" ng-model="packagePrice"/>  </li>
        <li><b>Total price</b><input type="text" ng-model="total"/>  </li>
    </form>
  </div>
</div>

JS:

function TestCtrl($scope) {
   $scope.$watch('price', function(newValue,oldValue){
    if(newValue != oldValue)
    {
        $scope.changeTotalPrice();
    }
});

$scope.changePrice = function(){
    var width = 0;
    var height = 0;
    var depth = 0;
    var priceCm = 0;

    width = $scope.width;
    height = $scope.height;
    depth = $scope.depth;
    priceCm = $scope.priceCm;

    if(width > 0 && height > 0 && depth > 0 && priceCm > 0)
    {
        $scope.price = width * height * depth * priceCm;
    }          
}

$scope.changeTotalPrice = function(){
    var price = 0;
    var packaging = 0;

    price = $scope.price;
    packaging = $scope.packagePrice;

    if(price > 0 && packaging > 0)
    {
        $scope.total = price*1 + packaging*1;
    }          
  }
}

样本:http://jsfiddle.net/rewnao6p/3/

javascript html angularjs angular-ngmodel
1个回答
0
投票

是的,这是更好的方法:因为您的总数取决于值的其余部分,所以动态计算总数

function TestCtrl($scope) {

 $scope.price = function(){
    var width = $scope.width;
    var height = $scope.height;
    var depth = $scope.depth;
    var priceCm = $scope.priceCm;

    if(width > 0 && height > 0 && depth > 0 && priceCm > 0)
    {
        return width * height * depth * priceCm;
    }          
}

 $scope.totalPrice = function(){        
    var price = $scope.price();
    var packaging = $scope.packagePrice;

    if(price > 0 && packaging > 0)
    {
        return price*1 + packaging*1;
    }          
 }

}

看小提琴:http://jsfiddle.net/g7p7ho6z/

© www.soinside.com 2019 - 2024. All rights reserved.