1

我正在尝试根据服务器响应创建动态表单。例如,我有 8 个按钮,每个按钮在单击时应生成具有不同输入类型的不同问卷。每个类别的问题都是从后端获取的,每个问题都有其类型,可以是单选、选择等。根据这些信息,我如何根据用户的按钮为特定问题集生成表单点击。我想到的一件事是根据单击的类别使用 ng-hide/show,但这将是一个非常糟糕的做法,因为 8 个类别(每个类别 8 个)总共有 64 个问题。任何帮助,将不胜感激。谢谢!!

响应如下:

{
  "code": 200,
  "data": {
    "id": "598ca3dac405bc378fc21764",
    "question_set_number": "QS1",
    "questions": [
      {
        "answers": [
          "Answer 1",
          "Answer 2",
          "Answer 3"
        ],
        "id": "59839d20c405bc411540a11d",
        "question_number": "Q1",
        "question_text": "Test question",
        "type": "radio"
      },
      {
        "answers": [
          "Answer 1",
          "Answer 2",
          "Answer 3"
        ],
        "id": "59839d2dc405bc411540a11e",
        "question_number": "Q2",
        "question_text": "Test question",
        "type": "check"
      }
    ]
  },
  "message": "successful",
  "status": "success"
}
4

1 回答 1

1

您可以循环基于服务器输入的表单输入,并像这样动态显示它们(此处的工作示例)。

HTML

<!-- click a button to see a form -->
<button data-ng-click="getQuestions('qs1')">Form 1</button>
<button data-ng-click="getQuestions('qs2')">Form 2</button>
<button data-ng-click="getQuestions('qs3')">Form 3</button>

<form action="">
  <input data-ng-repeat="item in questions" type={{item.type}}>
</form>

控制器

app.controller('MainCtrl', ['$scope', function ($scope) {

  $scope.questions = [];

  $scope.getQuestions = function (category) {

    //make service call based on category and return questions
    //$scope.questions = result of service

    //stubbed for example:
    $scope.questions = [
      {
        "answers": [
          "Answer 1",
          "Answer 2",
          "Answer 3"
        ],
        "id": "59839d20c405bc411540a11d",
        "question_number": "Q1",
        "question_text": "Test question",
        "type": "radio"
      },
      {
        "answers": [
          "Answer 1",
          "Answer 2",
          "Answer 3"
        ],
        "id": "59839d2dc405bc411540a11e",
        "question_number": "Q2",
        "question_text": "Test question",
        "type": "checkbox" //this was check, needed to be checkbox - either update service or manipulate it on your end
      }
    ];

  };


}]);

这样做显示了动态显示输入的概念,同时只编写一个输入字段。如果服务发送它,您可以添加更多。如果您要处理多种输入类型,我建议制作一个简单的动态输入指令来处理所有这些逻辑,然后简单地将类型传递给指令。我在这里有一个工作示例,但这就是概念。我也可以帮助你解决这个逻辑。

于 2017-08-11T16:11:26.953 回答