如何使用Angular JS实现点击添加按钮生成相同表单?
实现AngularJS动态添加申请人表单
问题描述
我是AngularJS新手,现有一个申请人表单及添加按钮,需求为点击添加按钮时,在当前表单下方生成一个完全相同的表单。当前页面显示一个申请人表单,右上角有"Add"按钮。
解决方案
核心思路是用AngularJS的ng-repeat指令遍历申请人数据数组,点击添加按钮时向数组推入新的空对象,自动渲染新表单,具体实现如下:
- 控制器初始化数据模型
在AngularJS控制器中定义数组存储申请人信息,初始添加一个空对象作为默认表单的数据载体:
angular.module('app', []) .controller('ApplicantController', function($scope) { // 初始化申请人数组,默认包含一个空表单 $scope.applicants = [{}]; // 添加新表单的方法 $scope.addApplicant = function() { $scope.applicants.push({}); }; });
- 修改HTML渲染动态表单
将原表单放入ng-repeat循环中,绑定添加按钮的点击事件,同时移除重复的id(避免DOM标识冲突):
<div class="row" ng-controller="ApplicantController"> <header class="panel-heading"> <h5 class="panel-title" style="padding-left: 1.5rem;"> <b>APPLICANTS</b> <input class="btn btn-primary" style="float:right" type="button" value="Add" ng-click="addApplicant()" /> </h5> <hr> </header> <!-- 遍历申请人数组,生成对应表单 --> <div class="panel-body" ng-repeat="applicant in applicants track by $index"> <div class="container"> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label class="control-label">Name</label> <div> <input type="text" class="form-control" ng-model="applicant.txtFullName"> </div> </div> </div> <div class="col-md-6"> <div class="form-group"> <label class="control-label">Nationality</label> <div> <input type="text" class="form-control" ng-model="applicant.txtNationality"> </div> </div> </div> </div> <div class="row"> <div class="col-md-4"> <div class="form-group"> <label class="control-label">Pin Code</label> <div> <input type="text" class="form-control" ng-model="applicant.txtPincode"> </div> </div> </div> <div class="col-md-4"> <div class="form-group"> <label class="control-label">House No.</label> <div> <input type="text" class="form-control" ng-model="applicant.txtHouseNo"> </div> </div> </div> </div> <!-- 可选:添加删除当前表单的按钮 --> <div class="row" style="margin-top:1rem;"> <div class="col-md-12"> <button class="btn btn-danger" ng-click="applicants.splice($index, 1)" ng-disabled="applicants.length === 1">删除</button> </div> </div> <hr> </div> </div> </div>
关键说明
ng-repeat="applicant in applicants track by $index":遍历数组生成表单,track by $index避免空元素导致的重复渲染报错。- 每个表单的
ng-model绑定到数组对应对象的属性,确保各表单数据独立不冲突。 - 移除了原代码中重复的
id="inputDefault",DOM中id必须唯一,否则会引发元素选择异常。
内容的提问来源于stack exchange,提问作者Meet Shah
相关产品推荐
相关产品推荐

