[英]AngularJS: single select between multiple checkbox
我試圖在復選框上強制單選,類似於html“select”
我有一個簡單的html表:
<tr ng-repeat="subscription in entities">
<td>
<input type="checkbox" ng-checked="isChecked(subscription)" ng-click="toggleSelection(subscription)"/>
</td>
</tr>
然后我有一些簡單的控制器函數用於上面的指令:
$scope.isChecked = function(entity) {
return $scope.checkedEntity === entity;
};
$scope.toggleSelection = function(entity) {
entity.checked = !entity.checked;
if (entity.checked) {
$scope.checkedEntity = entity;
} else {
$scope.checkedEntity = null;
}
};
不幸的是它不起作用,我想我剛剛發現了...... ng-click有0優先級,而ng-checked有100。
這個問題有優雅的解決方案嗎?
將ng-model
綁定到subscription.checked
,並使用ng-click
取消選中除單擊之外的所有訂閱。 由於這些是復選框,因此單擊的按鈕將自動切換。
<tr ng-repeat="subscription in entities">
<td>
<input ng-model="subscription.checked" ng-click="updateSelection($index, entities)" type="checkbox" />
</td>
</tr>
您可以使用plain for
循環,但angular的forEach
允許我們將每個項目別名為subscription
並提高可讀性:
$scope.updateSelection = function(position, entities) {
angular.forEach(entities, function(subscription, index) {
if (position != index)
subscription.checked = false;
});
}
這是一個工作演示: http : //plnkr.co/edit/XD7r6PoTWpI4cBjdIZtv?p = preview
<!DOCTYPE html> <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> <script> angular.module('app', []).controller('appc', ['$scope', function($scope) { $scope.selected = 'other'; } ]); </script> </head> <body ng-app="app" ng-controller="appc"> <label>SELECTED: {{selected}}</label> <div> <input type="checkbox" ng-checked="selected=='male'" ng-true-value="'male'" ng-model="selected">Male <br> <input type="checkbox" ng-checked="selected=='female'" ng-true-value="'female'" ng-model="selected">Female <br> <input type="checkbox" ng-checked="selected=='other'" ng-true-value="'other'" ng-model="selected">Other </div> </body> </html>
我使用下面的代碼來實現類似的功能。 訣竅是使用ng-click ,這可以很好地產生這種效果。 checkbox-1和checkbox-2本質上是布爾值。
<form>
<input type="checkbox" ng-click="checkbox-2 = false" ng-model="checkbox-1" >
<input type="checkbox" ng-click="checkbox-1 = false" ng-model="checkbox-2" >
</form>
在我的頭頂,我建議你選擇三個選項之一。
我選擇3 - 我總是喜歡利用原生輸入元素。
<tr ng-repeat="subscription in entities">
<td><input type="radio"
ng-model="selection"
name="subscriptionRadio"
value="{{subscription}}"/>
</td>
</tr>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.