2017-01-07 16 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

はい@マキシムスそれはここにあります:https://plnkr.co/edit/m35iYTFdh3G5v3IRghRI?p=preview – proktovief

+0

[私の答え](http://stackoverflow.com/a/41525688/2545680)を参照してください –

答えて

1

あなたはhtmlの設定が正しいです、あなたはちょうどそれが正しく選択した値を読み取っていません。最初の質問のために選択した答えを得るには、次のコマンドを使用します。あなたはng-modelquestion.valorを入れているときので

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

それはだ - それは実際に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、私の答えは助けましたか? –

関連する問題