How do checkbox behave like radio in ng-repeat?

Asked

Viewed 53 times

0

I’m trying to make a checkbox behave like a radio, but I’m not getting a few examples but I don’t understand how it works. If anyone can help me. I 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>

  • That you select one and uncheck the others?

  • That never gets more than one option selected.

1 answer

1

Create a control variable, where the value of the selected item will be default and after the click only the selected item is the only one with selection. This only happens if the selection click is to check the element backwards are all without selection. 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>
<div data-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 variable name
  • The name of your controller should start with minuscule type mainCtrl.
  • An example of suggestive names in the case of my example is checkName and setCheckName That’s good to relate to what you’re doing.
  • 1

    Thank you so much! I forgot to thank you. it worked.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.