【问题标题】:Add directive dynamically when using angular-formly使用角度形式时动态添加指令
【发布时间】:2016-01-12 00:47:10
【问题描述】:

添加一些指令的最佳方式是什么,例如将angular-formly 与自定义模板一起使用时,ng-focus-if 有条件地添加到表单的输入元素?

我想这样使用它:

$scope.formFields = [
  {
    key: 'email',
    type: 'input',
    templateOptions: {
      type: 'email',
      placeholder: 'Your E-Mail address',
      required: true,
      focusIf: 'some-expression' // <--- optional directive configuration here
    }
  }
];

这个想法是仅在实际提供配置选项时应用指令。

【问题讨论】:

  • 你会想要查看ngModelAttrs。这有点复杂,但是通过定义一个将其定义为 defaultOption 的自定义类型,您可以完成您正在寻找的内容。查看UI Mask 示例。
  • 你好肯特!谢谢你把我推向正确的方向!只是想告诉你,Formly 真的很棒而且非常灵活。我喜欢 Angular,但表单对我来说一直是一个巨大的痛苦,现在一切都解决了,多亏了你。我已经使用我的 ngFocusIf 集成创建了一个 JSBin,请随时根据您的需要对其进行编辑并将其添加到示例列表中。干杯! jsbin.com/vimayu/3/edit?html,js,output

标签: angularjs angular-formly


【解决方案1】:

您可以使用 ngModelAttrsangular-formly 属性与 ng-focus-if 属性或任何其他自定义属性结合起来。

在你的情况下,你的代码应该是这样的:

 $scope.formFields = [ {
        key: 'email',
        type: 'input',
         ngModelAttrs: {
              focusIf: {
                attribute: 'focus-if'   //directive declaration
              }
            },
        templateOptions: {
          type: 'email',
          placeholder: 'Your E-Mail address',
          focusIf: '', //directive default value
          required: true           
        }       
      }]

这是一个可以帮助你的working demo

【讨论】:

    【解决方案2】:

    感谢@kentcdodds 和@aitnasser,我已经设法弄清楚如何实现所需的行为。

    只是想在这里分享扩展版本。

    这个想法是在定义你的类型时使用ngModelAttrs 属性:

    formlyConfigProvider.setType({
      name: 'input',
      template: '<input ng-model="model[options.key]">',
      defaultOptions: {
        ngModelAttrs: {
          focusIf: {
            attribute: 'focus-if'
          }
        }
      }
    });
    

    确保不要为focusIf 提供默认值。默认情况下,这将阻止在输入元素上添加指令。

    然后在你的字段上设置所需的表达式:

    $scope.formFields = [
     {
       key: 'email',
       type: 'input',
       templateOptions: {
         type: 'email',
         required: true,
         placeholder: 'E-Mail',
         focusIf: 'true' // Or any other Angular expression
       }
     }
    ];
    

    随意玩这个JSBin

    【讨论】:

      猜你喜欢
      • 2021-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多