AngularJS-Encuadernación de botones de opción a modelos con valores booleanos


Tengo un problema al vincular botones de opción a un objeto cuyas propiedades tienen valores booleanos. Estoy tratando de mostrar las preguntas del examen recuperadas de un resource recurso.

HTML:

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

JS:

$scope.question = {
    questionText: "This is a test question.",
    choices: [{
            id: 1,
            text: "Choice 1",
            isUserAnswer: false
        }, {
            id: 2,
            text: "Choice 2",
            isUserAnswer: true
        }, {
            id: 3,
            text: "Choice 3",
            isUserAnswer: false
        }]
};   

Con este objeto de ejemplo, la propiedad "isUserAnswer: true" no hace que se seleccione el botón de opción. Si encapsulo los valores booleanos entre comillas, funciona.

JS:

$scope.question = {
    questionText: "This is a test question.",
    choices: [{
            id: 1,
            text: "Choice 1",
            isUserAnswer: "false"
        }, {
            id: 2,
            text: "Choice 2",
            isUserAnswer: "true"
        }, {
            id: 3,
            text: "Choice 3",
            isUserAnswer: "false"
        }]
};   

Desafortunadamente mi servicio REST trata esa propiedad como un booleano y será difícil cambiar la serialización JSON para encapsular esos valores entre comillas. ¿Hay otra forma de configurar el enlace del modelo sin cambiar la estructura de mi modelo?

Aquí está el jsFiddle mostrando objetos que no funcionan y que funcionan

Author: n daniel, 2013-06-06

7 answers

El enfoque correcto en Angularjs es usar ng-value para valores no string de modelos.

Modifica tu código así:

<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: Directamente de la boca del caballo

 360
Author: kumar_harsh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-21 13:50:03

Ese es un enfoque extraño con isUserAnswer. ¿Realmente va a enviar las tres opciones de vuelta al servidor, donde recorrerá cada una de ellas comprobando isUserAnswer == true? Si es así, puedes probar esto:

Http://jsfiddle.net/hgxjv/4/

HTML:

<input type="radio" name="response" value="true" ng-click="setChoiceForQuestion(question1, choice)"/>

JavaScript:

$scope.setChoiceForQuestion = function (q, c) {
    angular.forEach(q.choices, function (c) {
        c.isUserAnswer = false;
    });

    c.isUserAnswer = true;
};

Alternativamente, te recomendaría cambiar tu táctica:

Http://jsfiddle.net/hgxjv/5/

<input type="radio" name="response" value="{{choice.id}}" ng-model="question1.userChoiceId"/>

De esa manera puede enviar {{question1.userChoiceId}} de vuelta al servidor.

 20
Author: Langdon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-06-06 19:38:55

Hola espero que te ayude.

 <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>
 10
Author: Ronel Gonzales,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-04 11:34:06

Intenté cambiar value="true" a ng-value="true", y parece funcionar.

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

También, para conseguir que ambas entradas funcionen en su ejemplo, tendría que dar un nombre diferente a cada entrada {por ejemplo, response debería convertirse en response1 y response2.

 7
Author: seung,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-31 13:42:27

Puedes echar un vistazo a esto:

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

Este tipo escribió una directiva personalizada para evitar el problema de que "true" y "false" son cadenas, no booleanos.

 1
Author: Karen Zilles,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-06-06 20:14:56

La forma en que se configuran sus radios en el violín - compartiendo el mismo modelo - hará que solo el último grupo muestre una radio marcada si decide citar todos los valores truthy. Un enfoque más sólido implicará dar a los grupos individuales su propio modelo, y establecer el valor como un atributo único de las radios, como el id:

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

Aquí está una representación del nuevo html:

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

Y un violín.

 0
Author: rGil,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-06-06 19:46:33

Si está utilizando una variable booleana para enlazar el botón de opción. por favor, consulte el siguiente código de ejemplo

<div ng-repeat="book in books"> 
<input type="radio" ng-checked="book.selected"  
ng-click="function($event)">                        
</div>
 0
Author: Sahitya M,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-11 09:29:01