繁体   English   中英

如何在 angularjs 中预选单选按钮

[英]How to pre-select radio buttons in angularjs

当我的模型值为true我希望在加载时选择单选按钮,但反过来发生。 所有false模型都被选中。 怎么解决这个问题。

http://plnkr.co/edit/DIYm4vBM3srdS61K6EPA?p=preview

angular.module('radioExample', [])
      .controller('ExampleController', ['$scope',
        function($scope) {
          $scope.kind = [{
            name: 'task',
            selected: false
          }, {
            name: 'bug',
            selected: false
          }, {
            name: 'other',
            selected: true
          }, {
            name: 'rfe',
            selected: false
          }]
          $scope.$watch('kind', function() {
            console.log('changed', JSON.stringify($scope.kind, null, 2))
          }, true)

        }
      ]);

使用ng-value这是角度无线电的文档

<input type="radio" name="" id="" value="" ng-model="k.selected" ng-value="true" />

然后,如果ng-valuetrue ,并且model值也为true则将选中此复选框

这是更新演示

<input type="checkbox" id="rempass" ng-model="rememberMe" ng-checked="rememberMeUserInfoCheck()" >  $scope.rememberMeUserInfoCheck=function() { return true; } 

这对我有用

我修理了pl

 <form name="myForm" ng-controller="ExampleController">
    <br />all 'false' radio buttons are selected when 'value' is used -------------
    <br />
    <div ng-repeat="k in kind">
      <input type="radio" name="" id="" value="" ng-model="!k.selected" value="k.selected" />{{k.name}}
    </div>
    <br />all radio buttons are selected when 'ng-value' is used -------------
    <br />
    <div ng-repeat="k in kind">
      <input type="radio" name="" id="" value="" ng-model="k.selected" ng-value="k.selected" />{{k.name}}
    </div>
</form>

您说对了...。只需添加一个! 因此该模型将采用范围值的反面...因为您同时使用它们,我想它不会伤害您的代码

ng-checked =“ true”添加到您的单选框

`<input type="radio" ng-model="modelName" name="radioName" value="value1" ng-checked="true">`

对于那些使用FormGroupFormControl

在模板中:

  1. 添加formControlName = sameNameforAllRadioButtonsOfAChoice作为单选按钮input标签的属性。
  2. 还要添加value = "true"value = "false" (你也可以用数字和字符串来做,但我会继续用布尔值)。

在组件中:

  1. 将名称(例如sameNameforAllRadioButtonsOfAChoice添加到您的 FormGroup 中:

myForm = new FormGroup({sameNameforAllRadioButtonsOfAChoice: new FormControl('false')})

这将默认值设置为false 在FormControl中,注意写成字符串!

奖励 - 如果您需要验证:

  1. import { FormControl, FormGroup, Validators } from '@angular/forms';
  2. myForm = new FormGroup({sameNameforAllRadioButtonsOfAChoice: new FormControl('false', [Validators.required])})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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