Radio buttons plus a text field in Angular.js

前端 未结 2 1083
有刺的猬
有刺的猬 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: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:

    
    

    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.

    
    

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

    The chosen color is {{color}} - {{other}}
    

    Plunkr

提交回复
热议问题