从JSON创建动态表单

时间:2017-01-06 19:16:54

标签: javascript angularjs json forms

我正在使用3个嵌套的ng-repeat,用于显示几个问题及其相应的答案。直到这里很好,但我必须创建一个表单来保存答案,这是什么适当的方式呢?我正在测试:

<form>
    <div class="panel panel-default" ng-repeat="section in questionsTest">
        <div class="panel-heading">
            <h1>{{ section.name }}</h1>
            <h3 class="panel-title">{{ section.name }}. {{
                section.description }}</h3>
        </div>
        <div class="panel-body" ng-repeat="question in section.questions">
            {{ question.statement }}
            <div ng-repeat="answer in question.answers">
                <label class="radio-inline"> <input type="{{ answer.type }}" ng-model="test.idRadioButton"
                    name="{{ question.id }}" id="{{ answer.id }}" value="{{ answer.id }}">
                    {{ answer.valor }}
                </label>
            </div>
        </div>
    </div>
</form>

这是json:

{
    "section": [{
        "name": "Sección 1",
        "questions": [{
            "statement": "Primera pregunta",
            "answers": [{
                "valor": "1",
                "id": 3,
                "type": "radio"
            }, {
                "valor": "2",
                "id": 4,
                "type": "radio"
            }, {
                "valor": "3",
                "id": 7,
                "type": "radio"
            }, {
                "valor": "4",
                "id": 8,
                "type": "radio"
            }, {
                "valor": "5",
                "id": 9,
                "type": "radio"
            }, {
                "valor": "6",
                "id": 10,
                "type": "radio"
            }, {
                "valor": "7",
                "id": 11,
                "type": "radio"
            }],
            "id": 1
        }, {
            "statement": "Pregunta 3",
            "answers": [{
                "valor": "Si",
                "id": 1,
                "type": "radio"
            }, {
                "valor": "No",
                "id": 2,
                "type": "radio"
            }],
            "id": 3
        }, {
            "statement": "Pregunta 4",
            "answers": [{
                "valor": "Si",
                "id": 1,
                "type": "radio"
            }, {
                "valor": "No",
                "id": 2,
                "type": "radio"
            }],
            "id": 4
        }],
        "description": "description",
        "id": 1
    }

它根本不起作用,当我点击第一个问题时,所有其他问题也被点击了。我是棱角分明的新手,我不知道如何面对这个。感谢

现在

'工作',但我无法存储所有单击的单选按钮。这就是我控制器的方式:

$scope.question = {};
    $scope.testing = function(){
        console.log($scope.question);
    };

测试功能仅用于显示控制台上$ scope.question中存储的值。

1 个答案:

答案 0 :(得分:0)

每个问题都必须使用不同的模型。

使用:

ng-model="question.value"

我在这里做了一个有效的例子:https://plnkr.co/edit/SMYqvUNqXNJkW9x9ZmsB?p=preview

但是,您可能会对radio按钮的用途感到困惑。单选按钮仅允许一次选择一个。如果您需要多个,则必须将类型设置为checkbox