我正在学习角度并在我的程序中使用单选按钮。我发现了一个无法解释的问题。
<!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>
&#13;
此代码工作正常,但如果我在javascript代码中使$ scope.my等于空字符串或未定义,并使无线电输入HTML标记上的ng-model等于&#34; my&#34; ,然后可以选择多个单选按钮。原因是什么?
答案 0 :(得分:0)
<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 =“{{name}} - $ index”,它将以您想要的方式工作。如果保留相同的名称,则只能选择其中一个。