How to make checkbox behave like radio in ng-repeat?

0

I'm trying to make a checkbox behave like a radio, but I can not see some examples but I do not understand how it works. If anyone can help me. Thank you in advance for your attention!

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.pp = ["feminino", "masculino", "outros"];
});
<!DOCTYPE html>
<html ng-app="plunker">
  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="[email protected]" src="http://code.angularjs.org/1.1.5/angular.min.js"data-semver="1.1.5"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
  <h1> ng-repeat </h1>
  <div data-ng-repeat="p in pp">
    <input type="checkbox"> 
    {{p}}
  </div>
</body>
</html>
    
asked by anonymous 28.06.2018 / 20:31

1 answer

1

Create a control variable, where the value of the selected item will default and after the action of click only the selected item is the only one with selection. This all occurs only if the click of the selection is to check the element in reverse are all unselected. It's the simple way to solve this problem.

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.pp = ["feminino", "masculino", "outros"];
  $scope.checkName = '';
  $scope.setCheckName = function(name){
    $scope.checkName = name;
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script><h1>ng-repeat</h1><divdata-ng-app="plunker" data-ng-controller="MainCtrl">
  <div data-ng-repeat="p in pp">
    <input type="checkbox" 
      data-ng-click="setCheckName(p)"
      data-ng-checked="p==checkName">
    {{p}}
  </div>
</div>

Remarks:

  • The name of your module could be app with the same name as the variable
  • The name of your controller should begin with a minus type mainCtrl .
  • An example suggestive name in the case of my example is checkName and setCheckName this is good for relating what you are doing.
02.07.2018 / 20:48