【问题标题】:Generating dynamic conditional form fields from JSON - AngularJS1.x从 JSON 生成动态条件表单字段 - AngularJS1.x
【发布时间】:2018-05-25 20:17:39
【问题描述】:

我正在开发一个 AngularJS1.x 应用程序,我必须根据某些条件生成动态表单字段。整个动态表单字段类型、字段验证、条件都来自 JSON。字段类型可以是文本框、选择框、日期选择器、单选按钮或复选框。

努力实现: 我正在尝试一个更简单的过程来根据条件生成表单字段。

每种字段类型有3个条件,

  • is_mandatory
  • is_editable
  • is_display

它们的值可以是,

  • 0(否)
  • 1(是)
  • 2(有条件)

例如,

is_display : 1, is_editable : 2, is_mandatory : 0

这意味着字段将可见可根据特定条件进行编辑并且它不是必填字段。 对于此字段作为基于条件的可编辑属性,它将检查另一个名为 editable_condition 的属性,该属性的值类似于,

editable_condition : 1.1. Introductory Questions|111_what_is_the_inspection_typ|Onsite

|分隔值之间的值是unique_id,即111_what_is_the_inspection_typ in this case

unique_id 代表另一个字段,如果该字段值与该字段的最后一个| 分隔值(即本例中的Onsite)匹配,则该字段将是可编辑的。

这是JSON的屏幕截图,

现在我的问题是处理这些条件以显示不同类型的字段(如复选框、单选按钮、文本框、日期选择器等)的最佳方法是什么。

【问题讨论】:

    标签: javascript jquery angularjs json


    【解决方案1】:

    您是否考虑过使用诸如angular-formly 之类的库,而不是尝试重新发明轮子。

    这将允许您通过 JSON 以声明方式指定表单,例如

    HTML

    <formly-form model="vm.user" fields="vm.userFields">
        <button type="submit" class="btn btn-default" ng-click="vm.submit(vm.user)">Submit</button>
    </formly-form>
    

    JS

    function YourCtrl() {
      var vm = this;
    
      vm.user = {};
    
      vm.userFields = [
        {
          key: 'email',
          type: 'input',
          templateOptions: {
            type: 'email',
            label: 'Email address',
            placeholder: 'Enter email'
          }
        },
        {
          key: 'password',
          type: 'input',
          templateOptions: {
            type: 'password',
            label: 'Password',
            placeholder: 'Password'
          }
        },
        {
          key: 'file',
          type: 'file',
          templateOptions: {
            label: 'File input',
            description: 'Example block-level help text here',
            url: 'https://example.com/upload'
          }
        },
        {
          key: 'checked',
          type: 'checkbox',
          templateOptions: {
            label: 'Check me out'
          }
        }
      ];
    }
    

    【讨论】:

    • 我使用的 JSON 来自后端。我将如何根据库将其转换为相应的 JSON 格式,angular-formly。
    • 客户端,您必须编写一个助手来将您的专有 JSON 格式转换为其形式上的等价物。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-07
    • 1970-01-01
    • 2013-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多