2

我创建了这个jsbin,其中有fieldGroup2 个字段。按下时有一个按钮调用AddRow,我正在尝试将另一个字段动态添加到fieldGroup.

Formly 可以做到这一点吗?此示例是它在我的解决方案中如何工作的简化版本。我将从 Rest 调用中获得所需的各种字段类型的列表。此调用返回的任何内容都将是需要添加到fieldGroup. 从小处着手...我只是想通过单击按钮添加一个字段。

4

1 回答 1

5

你的错误是试图推动一个字符串而不是一个对象。请参阅更正的 JSBin: http: //jsbin.com/weyowu/edit ?html,js,output


以更高级的方式,您可以制作一个重复部分(自定义模板)来动态添加/删除表单的部分:

查看更多高级用法:http ://angular-formly.com/#/example/advanced/repeating-section

请参阅示例片段:

/* global angular */
(function() {
  console.clear();

  'use strict';

  var app = angular.module('formlyExample', ['formly', 'formlyBootstrap'], function config(formlyConfigProvider) {
    var unique = 1;
    formlyConfigProvider.setType({
      name: 'repeatSection',
      templateUrl: 'repeatSection.html',
      controller: function($scope) {
        $scope.formOptions = {
          formState: $scope.formState
        };
        $scope.addNew = addNew;

        $scope.copyFields = copyFields;


        function copyFields(fields) {
          fields = angular.copy(fields);
          addRandomIds(fields);
          return fields;
        }

        function addNew() {
          $scope.model[$scope.options.key] = $scope.model[$scope.options.key] || [];
          var repeatsection = $scope.model[$scope.options.key];
          var lastSection = repeatsection[repeatsection.length - 1];
          var newsection = {};
          if (lastSection) {
            newsection = angular.copy(lastSection);
          }
          repeatsection.push(newsection);
        }

        function addRandomIds(fields) {
          unique++;
          angular.forEach(fields, function(field, index) {
            if (field.fieldGroup) {
              addRandomIds(field.fieldGroup);
              return; // fieldGroups don't need an ID
            }

            if (field.templateOptions && field.templateOptions.fields) {
              addRandomIds(field.templateOptions.fields);
            }

            field.id = field.id || (field.key + '_' + index + '_' + unique + getRandomInt(0, 9999));
          });
        }

        function getRandomInt(min, max) {
          return Math.floor(Math.random() * (max - min)) + min;
        }
      }
    });
  });


  app.controller('MainCtrl', function MainCtrl(formlyVersion) {
    var vm = this;
    // funcation assignment
    vm.onSubmit = onSubmit;

    // variable assignment
    vm.author = { // optionally fill in your info below :-)
      name: 'Joe Zhou',
      url: 'https://plus.google.com/u/0/111062476999618400219/posts' // a link to your twitter/github/blog/whatever
    };
    vm.exampleTitle = 'Repeating Section'; // add this
    vm.env = {
      angularVersion: angular.version.full,
      formlyVersion: formlyVersion
    };
    vm.options = {};

    init();

    vm.originalFields = angular.copy(vm.fields);

    // function definition
    function onSubmit() {
      alert(JSON.stringify(vm.model), null, 2);
    }


    function init() {
      vm.model = {
        keys: [{}, ]
      };

      vm.fields = [{
        type: 'repeatSection',
        key: 'keys',
        templateOptions: {
          btnText: 'Add another Field',
          fields: [{
            key: 'key1',
            type: 'input',
            templateOptions: {
              label: 'A Field'
            }
          }]
        }
      }];
    }
  });

})();
<!DOCTYPE html>
<html>

<head>
  <!-- Twitter bootstrap -->
  <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet">

  <!-- apiCheck is used by formly to validate its api -->
  <script src="//rawgit.com/kentcdodds/apiCheck.js/master/dist/api-check.js"></script>
  <!-- This is the latest version of angular (at the time this template was created) -->
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js"></script>

  <!-- This is the current state of master for formly core. -->
  <script src="https://rawgit.com/formly-js/angular-formly/latest/dist/formly.js"></script>
  <!-- This is the current state of master for the bootstrap templates -->
  <script src="//rawgit.com/formly-js/angular-formly-templates-bootstrap/master/dist/angular-formly-templates-bootstrap.js"></script>

  <title>Angular Formly Example</title>
</head>

<body ng-app="formlyExample" ng-controller="MainCtrl as vm">
  <div>
    <h1>angular-formly example: {{vm.exampleTitle}}</h1>
    <div>
      This demonstrates using <code>formly-form</code> inside of a template in order to accomplish repeating fields. It also uses <code>formly-field</code> inside of a template in order to accomplish an advanced layout.
    </div>
    <hr />
    <form ng-submit="vm.onSubmit()" novalidate>
      <formly-form model="vm.model" fields="vm.fields" form="vm.form" options="vm.options">
        <button type="submit" class="btn btn-primary submit-button" ng-disabled="vm.form.$invalid">Submit</button>
      </formly-form>
    </form>
    <hr />
    <h2>Model</h2>
    <pre>{{vm.model | json}}</pre>
    <h2>Fields <small>(note, functions are not shown)</small></h2>
    <pre>{{vm.originalFields | json}}</pre>
    <h2>Form</h2>
    <pre>{{vm.form | json}}</pre>
  </div>

  <div style="margin-top:30px">
    <small>
        This is an example for the
        <a href="https://formly-js.github.io/angular-formly">angular-formly</a>
        project made with ♥ by
        <strong>
          <span ng-if="!vm.author.name || !vm.author.url">
            {{vm.author.name || 'anonymous'}}
          </span>
          <a ng-if="vm.author.url" ng-href="{{::vm.author.url}}">
            {{vm.author.name}}
          </a>
        </strong>
        <br />
        This example is running angular version "{{vm.env.angularVersion}}" and formly version "{{vm.env.formlyVersion}}"
      </small>
  </div>

  <script type="text/ng-template" id="repeatSection.html">
    <div>
      <!--loop through each element in model array-->
      <div class="{{hideRepeat}}">
        <div class="repeatsection" ng-repeat="element in model[options.key]" ng-init="fields = copyFields(to.fields)">
          <formly-form fields="fields" model="element" form="form">
          </formly-form>
          <div style="margin-bottom:20px;">
            <button type="button" class="btn btn-sm btn-danger" ng-click="model[options.key].splice($index, 1)">
              Remove
            </button>
          </div>
          <hr>
        </div>
        <p class="AddNewButton">
          <button type="button" class="btn btn-primary" ng-click="addNew()">{{to.btnText}}</button>
        </p>
      </div>
  </script>
</body>

</html>

于 2015-09-23T14:50:45.947 回答