根据服务器的响应在 Angular 中创建动态表单

Dynamic form creation in Angular based on server's response

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

响应如下:

{
  "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"
}

您可以根据服务器输入循环遍历表单输入并像这样动态显示它们(工作示例 here)。

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
      }
    ];

  };


}]);

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