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

Bri*_*ian 15 javascript angularjs

我试图在复选框上强制单选,类似于html"select"

我有一个简单的html表:

<tr ng-repeat="subscription in entities">
    <td>
        <input type="checkbox" ng-checked="isChecked(subscription)" ng-click="toggleSelection(subscription)"/>
    </td>
</tr> 
Run Code Online (Sandbox Code Playgroud)

然后我有一些简单的控制器函数用于上面的指令:

$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;
    }
};
Run Code Online (Sandbox Code Playgroud)

不幸的是它不起作用,我想我刚刚发现了...... ng-click有0优先级,而ng-checked有100.

这个问题有优雅的解决方案吗?

j.w*_*wer 24

绑定ng-modelsubscription.checked,并ng-click取消选中除一个所有订阅点击.由于这些是复选框,因此单击的按钮将自动切换.

<tr ng-repeat="subscription in entities">
  <td>
    <input ng-model="subscription.checked" ng-click="updateSelection($index, entities)" type="checkbox" />
  </td>
</tr>
Run Code Online (Sandbox Code Playgroud)

您可以使用普通for循环,但angularforEach允许我们将每个项目作为别名subscription并提高可读性:

$scope.updateSelection = function(position, entities) {
  angular.forEach(entities, function(subscription, index) {
    if (position != index) 
      subscription.checked = false;
  });
}
Run Code Online (Sandbox Code Playgroud)

这是一个工作演示:http://plnkr.co/edit/XD7r6PoTWpI4cBjdIZtv?p = preview


小智 8

<!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>
Run Code Online (Sandbox Code Playgroud)