简体   繁体   English

使用 Angular.js 选中复选框时如何设置输入字段值

[英]How to set input field value when check box is checked using Angular.js

I need when i will be checked the check box the respective input field will have the required value.我需要在选中复选框时相应的输入字段将具有所需的值。 Let me show my code below.让我在下面显示我的代码。

<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 />

I need here when user will check the Five the input field will get 5 and when user will check Ten ,the input field value will be 10 .我需要在这里当用户选中Five时,输入字段将获得5 ,当用户选中Ten时,输入字段值将为10

use ng-true-value="" in checkbox在复选框中使用ng-true-value=""

Like this像这样

<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 />

JSFIDDLE

I thought maybe you meant to use radio instead of check boxes (since the color can be either 5 OR 10).我想也许你打算使用单选而不是复选框(因为颜色可以是 5 或 10)。 here's a working plnkr .这是一个工作plnkr

and the code:和代码:

<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: 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 />

https://jsfiddle.net/5s1bfjco/7/ https://jsfiddle.net/5s1bfjco/7/

Bind your checkbox inputs to ng-model as well, and then assign the value accordingly.也将您的复选框输入绑定到ng-model ,然后相应地分配值。 Something like this:像这样:

<input type="checkbox" name="favoriteColors" ng-model="isChecked.five"> Five
<input type="checkbox" name="favoriteColors" ng-model="isChecked.ten"> Ten

In your controller:在你的控制器中:

$scope.isChecked = {};
if ($scope.isChecked.five) {
  $scope.color = 5;
}
if ($scope.isChecked.ten) {
  $scope.color = 10;
}

It should automatically update your input value as you check/uncheck the checkboxes, due to two-way binding.由于双向绑定,它应该在您选中/取消选中复选框时自动更新您的输入值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM