AngularJS:从表单中获取价值

时间:2017-01-07 19:12:42

标签: javascript angularjs forms

我正在使用3个嵌套的ng-repeat来阅读json并显示几个问题和他的答案。直到这里它正在工作,但现在我正在尝试存储选择的答案并将其发送到API。我不知道为什么没有存储选定的答案。

这是我的观点:

<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="question.value"
                    name="{{ answer.id }}" id="{{ answer.id }}" value="{{ answer.id }}">
                    {{ answer.valor }}
                </label>-->
                <label class="radio-inline"> <input type="{{ answer.type }}" ng-model="question.valor"
                    name="{{ question.id }}" id="{{ answer.id }}" value="{{ answer.id }}">
                    {{ answer.valor }}
                </label>
            </div>
        </div>
    </div>
</form>

这是控制器:

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

$ scope.testing是一个测试函数,用于在控制台上查看$ scope.question

的值

1 个答案:

答案 0 :(得分:1)

你的HTML设置是正确的,你只是没有正确读取所选的值。要获得第一个问题的选定答案,请使用以下内容:

$scope.json.section[0].questions[0].value

这是因为当您将question.valor放入ng-model时 - 它实际上是n-th部分内的n-th个问题。这些n索引由原始数据结构$scope.json中的项目数定义。

要获取所有值,您可以迭代原始对象:

$scope.testing = function () {
    var answers = {sections: []};

    for (var i = 0; i < $scope.json.section.length; i++) {
        if (!answers.sections[i]) {
            answers.sections[i] = {answers: []};
        }

        for (var j = 0; j < $scope.json.section[i].questions.length; j++) {
            if (!answers.sections[i].answers) {
                answers.sections[i].answers = [];
            }

            answers.sections[i].answers[j] = $scope.json.section[i].questions[j].value
        }
    }
}