[英]How to set input field value when check box is checked using Angular.js
我需要在选中复选框时相应的输入字段将具有所需的值。 让我在下面显示我的代码。
<label class="checkbox-inline">
<input type="checkbox" name="favoriteColors"> Five
</label>
<label class="checkbox-inline">
<input type="checkbox" name="favoriteColors"> Ten
</label>
<input type="text" name="color" id="clr" ng-model="color" readonly />
我需要在这里当用户选中Five
时,输入字段将获得5
,当用户选中Ten
时,输入字段值将为10
。
在复选框中使用ng-true-value=""
像这样
<label class="checkbox-inline">
<input type="checkbox" ng-model="color" ng-true-value="5" ng-false-value="0" name="favoriteColors"> Five
</label>
<label class="checkbox-inline">
<input type="checkbox" ng-model="color" ng-true-value="10" ng-false-value="0" ng-model="color" name="favoriteColors"> Ten
</label>
<input type="text" name="color" id="clr" ng-model="color" readonly />
我想也许你打算使用单选而不是复选框(因为颜色可以是 5 或 10)。 这是一个工作plnkr 。
和代码:
<label class="checkbox-inline">
<input type="radio" name="favoriteColors" ng-model="data.color" value="5"> Five
</label>
<label class="checkbox-inline">
<input type="radio" name="favoriteColors" ng-model="data.color" value="10"> Ten
</label>
<input type="text" name="color" id="clr" ng-model="data.color" readonly />
js:
app.controller('MainCtrl', function($scope) {
$scope.data = { color: '' };
});
<label class="checkbox-inline">
<input type="checkbox" ng-click="color=5" name="favoriteColors"> Five
</label>
<label class="checkbox-inline">
<input type="checkbox" ng-click="color=10" name="favoriteColors"> Ten
</label>
<input type="text" name="color" id="clr" ng-model="color" readonly />
也将您的复选框输入绑定到ng-model
,然后相应地分配值。 像这样:
<input type="checkbox" name="favoriteColors" ng-model="isChecked.five"> Five
<input type="checkbox" name="favoriteColors" ng-model="isChecked.ten"> Ten
在你的控制器中:
$scope.isChecked = {};
if ($scope.isChecked.five) {
$scope.color = 5;
}
if ($scope.isChecked.ten) {
$scope.color = 10;
}
由于双向绑定,它应该在您选中/取消选中复选框时自动更新您的输入值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.