2017-01-07 56 views
0

我使用3個嵌套的ng-repeat讀取json並顯示幾個問題和他的答案。直到這裏工作,但現在我試圖存儲選擇的答案並將其發送到API。我不知道爲什麼選擇的答案沒有被存儲。AngularJS:從表單中獲取值

這是我的看法:

<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

+0

你可以把一個plunker? –

+0

是@Maximus它在這裏:https://plnkr.co/edit/m35iYTFdh3G5v3IRghRI?p=preview – proktovief

+0

請參閱[我的答案](http://stackoverflow.com/a/41525688/2545680) –

回答

1

你的HTML設置是正確的,你只是沒有正確地讀取它所選擇的值。要獲取第一個問題選擇的答案,使用以下命令:

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

這是因爲,當你把question.valorng-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 
     } 
    } 
} 
+0

是的,但我怎麼能獲得所有的價值?我仍然沒有得到它 – proktovief

+0

只是迭代它,看到我更新的答案 –

+0

@proktovief,我的答案幫助嗎? –