【问题标题】:using ng-repeat and indexing for textbox input对文本框输入使用 ng-repeat 和索引
【发布时间】:2017-11-07 17:05:59
【问题描述】:

我正在尝试将 ng-repeat 和索引用于 angularjs 和 mvc 中的问答场景。所以对于我的数据库,我有两个表:

  1. 问题

    • 问题
    • InputType(文本框、复选框、单选等)
  2. 答案

    • 回答

问题和答案表之间存在一对多的关系,因为对于一个问题,可以有来自许多不同人的许多答案。在我的 angularjs 中,我使用 $scope 变量和 get 方法从数据库中获取问题,使用 ng-repeat 重复 div 中的问题。这样做是这样的:

//Question

 $scope.Question_NetSuite = {
   Question1: '',
   input_type: ''
 }

//Answer:
$scope.SysIntClient =
  {
    SysInt_ID: '',
    ID: '',
    Answer: ''
  }

$http.get('/Home/getUserInfo')
  .then(function (response) {
    $scope.Question_NetSuite = response.data;
    console.log("status:" + response.status);
    console.log("data: " + $scope.Question_NetSuite);
  })

我的 div 和 html 如下所示:

<div class="row" ng-repeat="(index, question) in Question_NetSuite">
  Value: {{question.Question1}} 
  {{ index }}
  <div class="col-lg-6">
    <label class="labelQuestion" id="question_label" for="question_answer">
      {{question.Question1}}
    </label>
  </div>
  //This seems to be where I am struggling
  <input type="text" ng-model="SysIntClient.Answer" />
  Value: {{SysIntClient.Answer}}
</div>

我遇到的问题是我想将文本框中的答案输入链接到我从数据库中获取的问题。我是 angularjs 和 mvc 的新手,所以我知道我需要使用中继器,并且我需要将答案分配给与问题相同的索引。我只是不知道该怎么做。

您建议我如何将问题与答案联系起来?

【问题讨论】:

  • 是否有任何 ID 可以分配问题的答案?
  • 有。我在问题数据库中包含了一个 QuestionID,它作为外键链接到答案表。

标签: javascript jquery html angularjs


【解决方案1】:

使用索引是个坏主意。您需要在问题数组中传递问题 ID,并为每个答案对象传递问题 ID。像这样的:

$scope.questionsList = [
   {
      "id": 1,
      "name": "My first question"
   },
   {
      "id": 2,
      "name": "My second question"
   }
]


$scope.answersList = {
  "1": [   // question ID
    {
       "id": 1,
       "answer": "First answer for question id 1"
    },
    {
       "id": 2,
       "answer": "Second answer for question id 1"
    }
  ],
  "2": [  // question ID
    {
       "id": 1,
       "answer": "First answer for question id 2"
    }
  ]
} 

重复 questionsList,然后通过 answersList 获得当前 question.id:

<div ng-repeat="question in questionsList">
  [{{question.id}}]: {{question.name}}
  <ul>
    <li ng-repeat="answer in answersList[question.id]">
      [{{answer.id}}]: {{answer.answer}}
    </li>     
  </ul>      
</div>

这是一个有效的 plunkr:http://jsfiddle.net/0pafvrhu/

【讨论】:

  • 如果 li 是一个文本框,这是否可以同样工作?我还能用同样的方式映射答案吗?
  • 是的,当然。 &lt;li ng-repeat="answer in answersList[question.id]"&gt; &lt;input type="text" ng-model="answer" /&gt; &lt;/li&gt;
  • 我唯一关心的是问题是预先设置在数据库中的,因此填充问题数组很容易。我关心的是答案的映射(我需要从用户那里获得而不是数组)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-24
  • 2018-12-14
  • 1970-01-01
  • 2014-06-11
  • 2018-09-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多