我正在使用 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;
}
}
}
最佳答案
是的,这是一个更好的方法:因为你的总数取决于其余的值,动态计算总数
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;
}
}
}
参见 fiddle :http://jsfiddle.net/g7p7ho6z/
关于javascript - AngularJS - 多重绑定(bind) - 计算输入值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26585424/