简体   繁体   English

如何使用angularjs动态创建表单

[英]How to dynamically create a form using angularjs

I am trying to figure out how to dynamically create a form based on an array of fields returned from the server. 我试图弄清楚如何根据服务器返回的字段数组动态创建表单。

Something like this 像这样

[{
  id: "title",
  type: "text", /* Map to Input type=text */
  regex: "/^[a-zA-Z]+/"
},{
  id: "summary",
  type: "memo", /* Map to Textarea */
  regex: "/^[a-zA-Z]+/"
},{
  id: "priority",
  type: "list", /* Map to Select */
  options: [1,2,3,4,5]
}]

I cant figure out a nice way of doing this, even with ng-repeat. 即使使用ng-repeat,我也找不到解决这个问题的好方法。 Once the form has about 30 fields, and 15+ different input types, it gets very ugly. 一旦表单具有大约30个字段以及15种以上不同的输入类型,它将变得非常难看。

Whats the 'Angular' way to do this, or should i generate the controller.js and template.html dynamically on the server? 什么是“ Angular”方法来执行此操作,还是应该在服务器上动态生成controller.js和template.html?

Try this. 尝试这个。 It is not the answer, just an approach.Hope It may help You. 这不是答案,而只是一种方法。希望对您有帮助。

HTML: HTML:

<div ng-repeat="person in person">
<form class="form-group" name="signinForm">
<label>Name:
<input class="form-control" ng-model="person.name" type="text">
</label>
<label>Male:
<input class="form-control" ng-model="person.gender" name="gender{{$index}}" type="radio" value="male">
</label>
<label>Female:
<input class="form-control" ng-model="person.gender" name="gender{{$index}}" type="radio" value="female">
</label><br>
<label>Age
<input class="form-control" ng-model="person.age" type="number">
</label>
</form>
<button type="button" ng-click="addPerson()">Add More</button>
</div>

JS: JS:

 $scope.initialize = [{}];
    $scope.person = {};
    $scope.addPerson = function(){
        $scope.initialize.push({});// adding more similar fields.
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM