AngularJS - Binding radio buttons to models with boolean values

后端 未结 7 632
梦如初夏
梦如初夏 2020-12-02 06:30

I am having a problem binding radio buttons to an object whose properties have boolean values. I am trying to display exam questions retrieved from a $resource.

HTML

相关标签:
7条回答
  • 2020-12-02 07:11

    The correct approach in Angularjs is to use ng-value for non-string values of models.

    Modify your code like this:

    <label data-ng-repeat="choice in question.choices">
      <input type="radio" name="response" data-ng-model="choice.isUserAnswer" data-ng-value="true" />
      {{choice.text}}
    </label>
    

    Ref: Straight from the horse's mouth

    0 讨论(0)
  • 2020-12-02 07:27

    The way your radios are set up in the fiddle - sharing the same model - will cause only the last group to show a checked radio if you decide to quote all of the truthy values. A more solid approach will involve giving the individual groups their own model, and set the value as a unique attribute of the radios, such as the id:

    $scope.radioMod = 1;
    $scope.radioMod2 = 2;
    

    Here is a representation of the new html:

    <label data-ng-repeat="choice2 in question2.choices">
                <input type="radio" name="response2" data-ng-model="radioMod2" value="{{choice2.id}}"/>
                    {{choice2.text}}
            </label>
    

    And a fiddle.

    0 讨论(0)
  • 2020-12-02 07:29

    I tried changing value="true" to ng-value="true", and it seems to work.

    <input type="radio" name="response2" data-ng-model="choice.isUserAnswer" ng-value="true" />

    Also, to get both inputs to work in your example, you'd have to give different name to each input -- e.g. response should become response1 and response2.

    0 讨论(0)
  • 2020-12-02 07:31

    You might take a look at this:

    https://github.com/michaelmoussa/ng-boolean-radio/

    This guy wrote a custom directive to get around the issue that "true" and "false" are strings, not booleans.

    0 讨论(0)
  • 2020-12-02 07:32
     <label class="rate-hit">
         <input type="radio" ng-model="st.result" ng-value="true" ng-checked="st.result">
         Hit
     </label>
     &nbsp;&nbsp;
     <label class="rate-miss">
         <input type="radio" ng-model="st.result" ng-value="false" ng-checked="!st.result">
         Miss
     </label>
    
    0 讨论(0)
  • 2020-12-02 07:34

    if you are using boolean variable to bind the radio button. please refer below sample code

    <div ng-repeat="book in books"> 
    <input type="radio" ng-checked="book.selected"  
    ng-click="function($event)">                        
    </div>
    
    0 讨论(0)
提交回复
热议问题