簡體   English   中英

AngularJS單選按鈕被多個選中

[英]Angularjs radio buttons become multiple selected

我正在學習角度並在程序中使用單選按鈕。 我發現了一個我無法解釋的問題。

 <!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。 因此,例如id =“ {{name}}-$ index” ,它將按您想要的方式工作。 如果您保留相同的名稱,則只能選擇其中之一。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM