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