Angularjs 单选按钮变为多个选定状态

Angularjs radio buttons become multiple selected

本文关键字:状态 单选按钮 Angularjs      更新时间:2023-09-26

我正在学习角度并在程序中使用单选按钮。我发现了一个我无法解释的问题。

<!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>

这段代码工作正常,但是如果我在 javascript 代码中使 $scope.my 等于空字符串或未定义,并使无线电输入 HTML 标签上的 ng-model 等于"my",那么单选按钮可以多次选择。原因是什么?

<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>

可能是因为它们都有相同的 id - 更改它。因此,例如id="{{name}}-$index",它将按照您想要的方式工作。如果保留相同的名称,则只能选择其中一个。