【问题标题】:Add 2 input values and display result in another input box添加2个输入值并在另一个输入框中显示结果
【发布时间】:2020-06-03 01:28:02
【问题描述】:
我是 AngularJS 的新手。想要从 2 个输入文本框中获取值,添加它们,然后在第三个文本框中显示它们。
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
$scope.sum = ( $scope.a + $scope.b );
});
<!DOCTYPE html>
<html lang="en">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="formCtrl">
<form>
<input ng-model="a" type="number">
<input ng-model="b" type="number">
<input ng-model="sum" type="number">
</form>
</div>
</body>
</html>
【问题讨论】:
标签:
html
angularjs
data-binding
【解决方案1】:
使用ng-change 指令:
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
$scope.a = $scope.b = $scope.sum = 0;
$scope.updateSum = function() {
$scope.sum = $scope.a + $scope.b;
};
});
<!DOCTYPE html>
<html lang="en">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="formCtrl">
<form>
A=<input ng-model="a" ng-change="updateSum()" type="number"><br>
B=<input ng-model="b" ng-change="updateSum()" type="number"><br><br>
Sum=<input ng-model="sum">
</form>
</div>
</body>
</html>
【解决方案2】:
您无需创建任何功能即可实现,只需将value = {{a+b}} 放入您的第三个输入标签中
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
$scope.sum = ( $scope.a + $scope.b ); // this will assign value sum only when one time- when controller init happen and that time a and b both is undefined
});
<!DOCTYPE html>
<html lang="en">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="formCtrl">
<form>
<input ng-model="a" type="number">
<input ng-model="b" type="number">
<input value="{{a + b}}" type="number">
</form>
</div>
</body>
</html>