Javascript 获取角度js中两个下拉值的平均值
如何查看两个选择框的模型(不使用ng更改),如果选中,应计算平均值并在文本字段中显示答案:例如 HTML I:Javascript 获取角度js中两个下拉值的平均值,javascript,angularjs,watch,Javascript,Angularjs,Watch,如何查看两个选择框的模型(不使用ng更改),如果选中,应计算平均值并在文本字段中显示答案:例如 HTML I: <select ng-model="box1" ng-options="item for item in boxA"></select> HTML II: <select ng-model="box2" ng-options="item for item in boxB"></select> 文本框: <input type="
<select ng-model="box1" ng-options="item for item in boxA"></select>
HTML II:
<select ng-model="box2" ng-options="item for item in boxB"></select>
文本框:
<input type="text" ng-model="answer">
如果您不想使用ng change,我的建议是留出一段时间来检查控制器中的值
$interval(function() {
if($scope.box1 && $scope.box2) {
$scope.answer = (parseInt($scope.box1) + parseInt($scope.box2))/2
}
}, 1000);
为了获得更好、角度更大的效果,您可以使用$watchCollection:
$scope.$watchCollection('[box1, box2]',function(newValues,oldValues){
console.log('Box1: '+newValues[0]+', Box2: '+newValues[1]);
$scope.answer = (parseInt(newValues[0]) + parseInt(newValues[1])/2; //(or replace 2 with newValues.length if you plan to add more models into watch and get an average of more;)
});
您可以使用以下内容观看
$scope.box1
和$scope.box2
:
$scope.$watch('box1', function(value){
$scope.answer = calculateAverage(value, $scope.box2);
});
$scope.$watch('box2', function(value){
$scope.answer = calculateAverage(value, $scope.box1);
});
看看这个小提琴演示:你试过什么?我假设第二个
$scope.boxA
是$scope.boxB
?
$scope.$watchCollection('[box1, box2]',function(newValues,oldValues){
console.log('Box1: '+newValues[0]+', Box2: '+newValues[1]);
$scope.answer = (parseInt(newValues[0]) + parseInt(newValues[1])/2; //(or replace 2 with newValues.length if you plan to add more models into watch and get an average of more;)
});
$scope.$watch('box1', function(value){
$scope.answer = calculateAverage(value, $scope.box2);
});
$scope.$watch('box2', function(value){
$scope.answer = calculateAverage(value, $scope.box1);
});