AngularJS radio button group with “other” option that includes a text field

后端 未结 2 770
萌比男神i
萌比男神i 2021-01-25 05:29

I have a form with three radio buttons in a group. The third radio button is \"Other\" and has a text field where the user can enter something in. I can make the radio button r

相关标签:
2条回答
  • 2021-01-25 05:42

    You can use ng-required. Something like

    <input type ="text" ng-required ="form.Program != 'other'">
    

    should work.

    Regarding your other issue, you have to employ some controller-logic and some kind of temporary variable for form.OtherProgram, using $watch for example.

    $scope.$watch('form.Program', function(mVal){
      if (angular.isUndefined($scope.form)) return; 
    
      if(mVal === 'other'){
         $scope.form.OtherProgram = $scope.tmVar;
      } else {
        if($scope.form.OtherProgram !== null){
          $scope.tmVar = $scope.form.OtherProgram;
          $scope.form.OtherProgram = null;
       }
     }
    });
    

    Plunker: http://plnkr.co/edit/npvUXpRhB5MYJOstwd88?p=preview

    0 讨论(0)
  • 2021-01-25 05:51

    Here's what I ended up with. It's a slight variation on hugo's answer. The main difference being that the "other" text stays visible on the screen. I just thought I'd document this as an alternative approach.

    <p>
        Program:
        <label><input type="radio" ng-model="form.Program" name="Program" value="option 1" required /> option 1</label>
        <label><input type="radio" ng-model="form.Program" name="Program" value="option 2" required /> option 2</label>
        <label><input type="radio" ng-model="form.Program" name="Program" value="Other" required /> Other</label>
        <input type="text" ng-model="OtherProgram" ng-disabled="form.Program != 'Other'" ng-change="form.OtherProgram = OtherProgram" ng-required="form.Program == 'Other'" name="Program_Other" />
        <input type="hidden" ng-model="form.OtherProgram" />
    </p>
    

    And then this $watch function in my controller:

    $scope.$watch('form.Program', function (mVal) {
        if (angular.isUndefined($scope.form)) return;
    
        if (mVal === 'Other') {
            $scope.form.OtherProgram = $scope.OtherProgram;
        } else {
            $scope.form.OtherProgram = null;
        }
    });
    
    0 讨论(0)
提交回复
热议问题