簡體   English   中英

AngularJS:在多個復選框之間單選

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

在我的頭頂,我建議你選擇三個選項之一。

  1. 編寫一個指令,為您設置復選框並管理其中的狀態。 這並不理想,因為您正在將關於模型的規則(僅應檢查一個訂閱)轉換為DOM操作問題。
  2. 構建模型,使得只有一個訂閱標記為活動。 這很棘手,因為在更改時修改模型將啟動另一個摘要周期,而不是您想要的。
  3. 使用單選按鈕而不是復選框。 這將為您提供您想要的模態。 :-P

我選擇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.

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