使用 angular-formly 时动态添加指令

Add directive dynamically when using angular-formly

添加一些指令的最佳方式是什么,例如ng-focus-if conditionally to the form's input element when using angular-formly 使用自定义模板?

我想这样使用它:

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

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

您可以使用 angular-formly 属性与 ng-focus-if 属性或任何其他自定义属性组合18=]ngModelAttrs.

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

 $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,可以帮助到你:

感谢@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