AngularJS:在多个复选框之间单选

AngularJS: single select between multiple checkbox

本文关键字:复选框 之间 单选 AngularJS      更新时间:2023-09-26

我试图在复选框上强制进行单一选择,类似于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时的优先级为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>

您可以使用普通的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点击,这可以很好地实现这一点复选框-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>