问题描述
angular.js中一组复选框,怎么实现选中其中一个,其他不能选?
问题解答
回答1:<!DOCTYPE html><html lang='en' ng-app='app'><head> <meta charset='UTF-8'> <title>Document</title> <link href='http://cdn.bootcss.com/bootstrap/3.3.6/css/bootstrap.min.css' rel='stylesheet'></head><body> <p ng-controller='demo'><p>当前值: {{hobby}}</p><ul> <li ng-repeat='i in [1,2,3]'><label>吃:</label><input type='checkbox' ng-click='check(i)' ng-disabled='hobby == i' ng-checked='hobby == i' /> </li></ul> </p> <script src='http://cdn.bootcss.com/angular.js/1.5.7/angular.min.js'></script> <script>angular.module(’app’, []).controller(’demo’, [’$scope’, function ($scope) { $scope.hobby = 1; $scope.check = function (i) {$scope.hobby = i; }}]); </script></body></html>回答2:
ng-model需要一致。用value控制内容.
<script> angular.module(’radioExample’, []) .controller(’ExampleController’, [’$scope’, function($scope) { $scope.color = {name: ’blue’ }; $scope.specialValue = {'id': '12345','value': 'green' }; }]);</script><form name='myForm' ng-controller='ExampleController'> <label> <input type='radio' ng-model='color.name' value='red'> Red </label><br/> <label> <input type='radio' ng-model='color.name' ng-value='specialValue'> Green </label><br/> <label> <input type='radio' ng-model='color.name' value='blue'> Blue </label><br/> <tt>color = {{color.name | json}}</tt><br/> </form> Note that `ng-value='specialValue'` sets radio item’s value to be the value of `$scope.specialValue`.回答3:
以下代码就是个思路,有很多问题,比如我发现的,列表不能抽取出来,用ng-for不可行。.disabled需要自己去调节样式。
<!DOCTYPE html><html lang='en' ng-app='app'><head> <meta charset='UTF-8'> <title>Document</title> <link href='https://cdn.bootcss.com/bootstrap/3.3.6/css/bootstrap.min.css' rel='stylesheet'></head><body> <p ng-controller='demo'><p>当前值: {{hobby}}</p><ul> <li><label>吃:</label><input type='checkbox' ng-true-value='1' ng-model='hobby' ng- ng-change='handleCheckbox($event)' /> </li> <li><label>睡:</label><input type='checkbox' ng-true-value='2' ng-model='hobby' ng- ng-change='handleCheckbox($event)' /> </li></ul> </p> <script src='https://cdn.bootcss.com/angular.js/1.5.7/angular.min.js'></script> <script>angular.module(’app’, []) .controller(’demo’, [’$scope’, function ($scope) {$scope.hobby = false; }]); </script></body></html>

