简体   繁体   中英

Angularjs radio buttons become multiple selected

I am learning angular and use radio button in my program. I found a problem that I can't explain it.

 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <link href="bower_components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"> <link href="bower_components/bootstrap/dist/css/bootstrap-theme.min.css" rel="stylesheet"> <link href="bower_components/font-awesome/css/font-awesome.min.css" rel="stylesheet"> <script src="bower_components/angular/angular.min.js"></script> </head> <body ng-app = "myApp"> <div class="container" ng-controller="myController"> <div><p style="margin: 30px auto"></p></div> <label class="radio-inline" ng-repeat = "name in names" for = "{{name}}"> <input type="radio" ng-model="my.favorite" ng-value="name" id="{{name}}" name="favorite"></input> {{name}} </label> <p>Your favorite is {{my.favorite}}</p> <div> <select ng-model="choosenone" ng-options="method.value as method.label for method in contactMethods"> <option value="">Tel or Email</option> </select> <p>You choose {{choosenone}}</p> </div> </div> <script type="text/javascript"> angular.module('myApp',[]) .controller("myController",['$scope','$log',function ($scope,$log) { //radio choices $scope.names = ['pizza', 'unicorns', 'robots']; $scope.my = { favorite: 'unicorns' }; //select chocices $scope.contactMethods = [{value:"tel",label:"Tel."},{value:"email",label:"Email"}]; $scope.choosenone; }]); </script> </body> </html> 

This code works fine, but if I make $scope.my in the javascript code equal to an empty string or undefined, and make the ng-model on the radio input HTML tag equal to "my", then the radio buttons can be mutiple selected. What's the reason?

<label class="radio-inline" ng-repeat="name in names" for="{{name}}">
  <input type="radio" ng-model="my.favorite" ng-value="name" id="{{name}}" name="favorite" />
  {{name}}
</label>

Probably because they all have the same id - change that. So for example id="{{name}}-$index" and it will work the way you want. If you keep the same name, only one of them can be selected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM