Radio buttons plus a text field in Angular.js

前端 未结 2 1082
有刺的猬
有刺的猬 2021-01-19 04:44

Using AngularJS, I would like to create a list of options with radio buttons, the last of which has an empty text field labeled \'Other\' for inputing an option that is not

相关标签:
2条回答
  • 2021-01-19 05:30

    I made some very small modifications to your pen HERE.

    The short of it is, instead of having 'Other' as a value, i made it a blank option, with the input actually controlling the value.

    $scope.colors = [
          "Red",
          "Green",
          "Blue",
          ""
         ];
    

    html:

      <label >
         {{color || 'Other'}}
       </label>
      <input type="text" ng-model="$parent.color" ng-show="color==''">
    

    This allows the input to actually control the value of 'Other'...

    0 讨论(0)
  • 2021-01-19 05:33

    Add a separate scope property for the other text:

    $scope.other = '';
    

    Add a colorChanged() method which will be called when the color is changed. This will set the other text to empty if color is not 'Other':

    $scope.colorChanged = function () {
        if ($scope.color != 'Other') {
            $scope.other = '';
        }
    };
    

    This will also need to be called from changeColor(). I ended up changing changeColor to allow the color to be passed in. It otherwise defaults to red:

    $scope.changeColor = function(color){
        $scope.color = color || "Red";
        $scope.colorChanged();
    };
    

    Add ng-change="colorChanged()" to radio button:

    <input type="radio" ng-model="$parent.color" ng-value="color" id="{{color}}" name="color" ng-change="colorChanged()">
    

    Change the textbox to use other as the model. Use ng-focus to detect when textbox is focused and then set color to 'Other'. Doing this will select the radio button.

    <input type="text" ng-model="$parent.other" ng-show="color=='Other'" ng-focus="$parent.color = 'Other'"/>
    

    Update the display of the color to show the other text:

    The chosen color is <strong>{{color}}<span ng-if="color === 'Other' && other != ''"> - {{other}}</span></strong>
    

    Plunkr

    0 讨论(0)
提交回复
热议问题