簡體   English   中英

使用 Angular.js 選中復選框時如何設置輸入字段值

[英]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 />

JSFIDDLE

我想也許你打算使用單選而不是復選框(因為顏色可以是 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 />

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

也將您的復選框輸入綁定到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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM