Search code examples
angularjsangular-formly

Add directive dynamically when using angular-formly


What would be the best way to add some directive, e.g. ng-focus-if conditionally to the form's input element when using angular-formly with custom templates?

I would like to use it like this:

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

The idea is to apply the directive only when configuration option is actually provided.


Solution

  • You can combining angular-formly attributes with ng-focus-if attributes or any others custom attributes by using ngModelAttrs.

    in your case your code should be like:

     $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           
            }       
          }]
    

    this is a working demo that can help you: