Angular-Formly:在用户点击时动态添加表单字段 [英] Angular-Formly : Adding Form fields dynamically on user click

查看:28
本文介绍了Angular-Formly:在用户点击时动态添加表单字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将如何在表单中添加功能,以便用户可以通过单击添加"来添加更多输入字段.这使用 angular 形式库.

这是确切功能的示例,但仅使用 angularjs 完成.

动态添加表单字段

解决方案

查看此Plunker

这是您需要的示例.正如您在 plunker 中看到的,有一个 TextArea 可以在按钮点击时动态创建.创建的 TextAreas 也可以通过点击 remove 按钮删除.

请参阅下面的 HTML

<input type="button" class="btn btn-info" ng-click="addNewChoice()" value="添加问题"><div class="col-sm-4"><fieldset data-ng-repeat="choiceSet.choices track by $index 中的字段"><textarea rows="4" cols="50" ng-model="choiceSet.choices[$index]"></textarea><button type="button" class="btn btn-default btn-sm" ng-click="removeChoice($index)"><span class="glyphicon glyphicon-minus"></span>消除</fieldset>

JS如下

var app = angular.module('myApp', []);app.controller('inspectionController', function($scope, $http) {$scope.choiceSet = {选择:[]};$scope.quest = {};$scope.choiceSet.choices = [];$scope.addNewChoice = function() {$scope.choiceSet.choices.push('');};$scope.removeChoice = 函数(z){$scope.choiceSet.choices.splice(z, 1);};});

How would I go about adding the capability in the form so that the user can add more input fields by clicking the "Add". This using the angular formly library.

Here is an example of the exact feature but done using only angularjs.

Adding form fields dynamically

解决方案

See this Plunker

Here is an example of what you need. As you can see in the plunker, there is a TextArea which can be created dynamically on button click. The created TextAreas can also be removed with the remove button click.

See the HTML below

<div class="col-sm-10">
  <input type="button" class="btn btn-info" ng-click="addNewChoice()" value="ADD QUESTION">
  <div class="col-sm-4">
    <fieldset data-ng-repeat="field in choiceSet.choices track by $index">
      <textarea rows="4" cols="50" ng-model=" choiceSet.choices[$index]"></textarea>
      <button type="button" class="btn btn-default btn-sm" ng-click="removeChoice($index)">
        <span class="glyphicon glyphicon-minus"></span> REMOVE
      </button>
    </fieldset>
  </div>
</div>

and the JS will be as below

var app = angular.module('myApp', []);
app.controller('inspectionController', function($scope, $http) {
  $scope.choiceSet = {
    choices: []
  };
  $scope.quest = {};
  $scope.choiceSet.choices = [];
  $scope.addNewChoice = function() {
    $scope.choiceSet.choices.push('');
  };
  $scope.removeChoice = function(z) {
    $scope.choiceSet.choices.splice(z, 1);
  };
});

这篇关于Angular-Formly:在用户点击时动态添加表单字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆