如何在ng-repeat中选择多个单选按钮?

时间:2017-08-28 18:39:48

标签: javascript angularjs radio-button angularjs-ng-repeat

code in plunkr

<tr ng-repeat="item in items.options">
    <td width="90%" ng-bind="item.value" align="center" class="align-items-center"></td>
    <td width="10%" align="center">
    <input type="radio" id="enabled{{item.name}}" name="enabled{{item.name}}" ng-model="radio.selection" ng-change="dataforAccessRight(function.fncFunctionCode,'Y')"
        ng-value="1" />
</td>

我想创建一个菜单,我可以为使用ng-repeat重复的各种项目选择启用和禁用选项。

2 个答案:

答案 0 :(得分:0)

老实说,这个问题对我来说似乎很模糊。你要启用或禁用它是什么? 让我试着说明如何使用ng-repeat在表格中设置单选按钮。

这是HTML(注意我已经复制了问题中的单选按钮代码,因为我不知道你希望用它们完成什么):

 <table border=3>
  <tr ng-repeat="product in products">
    <td>{{product.id}}<input type ="radio"
                                   id = "enabled{{item.name}}"
                                   name = "enabled{{item.name}}"
                                   ng-model="radio.selection"
                                   ng-change="dataforAccessRight(function.fncFunctionCode,'Y')"
                                   ng-value="1"

                            /></td>
    <td>{{product.name}}</td>
  </tr>
</table>

.js代码:

 var app = angular.module("myShoppingList", []); 
app.controller("myCtrl", function($scope) {
    $scope.products = [{id:1,
                        name:"Milk"},
                        {id:2,
                        name:"Bread"},
                        {id:3,
                        name:"Cheese"}];
});

答案 1 :(得分:0)

我认为他想要问的是他想要一个通用开关来启用/禁用ng-repeat上的所有单选按钮。问题是单选按钮不应该一次全部选中,所以我会使用复选框。

点击此处查看此工作示例:

angular
  .module('app', [])
  .controller('TestController', function($scope) {
     
     $scope.items = [
      {
        label: 'Item 1',
        selected: true
      },
      {
        label: 'Item 2',
        selected: false
      },
      {
        label: 'Item 3',
        selected: false
      }
     ];
     
     this.toggleItems = function(context) {
        for(var i = 0; i < $scope.items.length; i++) {
          var item = $scope.items[i];
          
          item.selected = (context === 'SELECT ALL');
        }
     }
     
  });
a {
  cursor: pointer;
  display: inline-block;
  text-decoration: underline;
}

form {
  margin-top: 20px;
}

form label {
  display: block;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Universal toggle</title>
    <script src="https://code.angularjs.org/1.5.8/angular.min.js"></script>
</head>
<body ng-app="app">

<div ng-controller="TestController as ctrl">

  <a ng-click="ctrl.toggleItems('SELECT ALL')">
    Select all
  </a>
  
  <a ng-click="ctrl.toggleItems('DESELECT ALL')">
    Deselect all
  </a>

  <form>
     <label ng-repeat="item in items">
       <input type="checkbox" ng-model="item.selected"> {{item.label}}
     </label>
  </form>

</div>

</body>
</html>

这应该(如果我理解正确的话)你想要实现的目标。