我有长度和呼吸,基于o我正在计算面积(l * b),假设我有很多不同长度和呼吸的场,面积正在计算但我需要面积列的总和,所以如何添加一个新文本框中所有上述字段的总和???我需要所有num3(区域)的总和。
我的代码低于......
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myapp" ng-controller="MainCtrl">
<form data-ng-repeat="choice in choices">
Length:<input type="number" ng-model="num1" />
width: <input type="number" ng-model="num2" />
Area: <input id="area" type="number" ng-model="num3" placeholder="Area" value="{{ num1 * num2 }}" />
<button ng-show="$last" ng-click="removeChoice()">-</button>
</form>
<button ng-click="addNewChoice()">Add fields</button>
</div>
<script>
var app = angular.module('myapp', []);
app.controller('MainCtrl', function($scope) {
$scope.choices = [{id: 'choice1'}, {id: 'choice2'}];
$scope.addNewChoice = function() {
var newItemNo = $scope.choices.length+1;
$scope.choices.push({'id':'choice'+newItemNo});
};
$scope.removeChoice = function() {
var lastItem = $scope.choices.length-1;
$scope.choices.splice(lastItem);
};
});
</script>
</body>
</html>
答案 0 :(得分:0)
在你的情况下,我不知道一个简单的解决方案。
你不能用value =“{{val + val2}}”来做,因为它只用于显示值而不是改变模型。
可能的解决方案:
<form data-ng-repeat="choice in choices">
Length:<input type="number" ng-model="choice.length" />
width: <input type="number" ng-model="choice.width" />
Area: <input id="area" type="number" placeholder="Area" value="{{ choice.length * choice.width }}" />
<button ng-show="$last" ng-click="removeChoice()">-</button>
</form>
<button ng-click="addNewChoice()">Add fields</button>
Result : {{ sum() }}
在您的控制器中:
$scope.choices = [{id: 'choice1', length:0, width: 0}, {id: 'choice2', length:0, width: 0}];
$scope.addNewChoice = function() {
var newItemNo = $scope.choices.length+1;
$scope.choices.push({'id':'choice'+newItemNo});
};
$scope.removeChoice = function() {
var lastItem = $scope.choices.length-1;
$scope.choices.splice(lastItem);
};
$scope.sum = function() {
var sum = 0;
angular.forEach($scope.choices, function(choice) {
sum += choice.length * choice.width;
});
return sum;
}
答案 1 :(得分:0)
<form data-ng-repeat="item in choices">
Length:
<input type="number" ng-model="item.num1" /> width:
<input type="number" ng-model="item.num2" /> Area:
<input id="area" type="number" ng-model="num3" placeholder="Area" value="{{item.num1 * item.num2}}" />
<button ng-show="$last" ng-click="removeChoice()">-</button>
</form>
<span data-ng-bind="'Total Area:' + total()"></span>
</br>
<button ng-click="addNewChoice()">Add fields</button>
$scope.total = function() {
var total = 0;
angular.forEach($scope.choices, function(item) {
total += item.num1 * item.num2;
})
return total;
}