我正在使用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;
}
}
}
答案 0 :(得分: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;
}
}
}