Slava Fomin II
Slava Fomin II

Reputation: 28611

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.

Upvotes: 3

Views: 2413

Answers (2)

Slava Fomin II
Slava Fomin II

Reputation: 28611

I've managed to figure out how to achieve the desired behavior, thanks to @kentcdodds and @aitnasser.

Just wanted to share the extended version here.

The idea is to use ngModelAttrs property when defining your type:

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

Make sure not to provide the default value for the focusIf. This will prevent addition of the directive on the input element by default.

And then set the required expression on your field:

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

Feel free to play with this JSBin.

Upvotes: 2

aitnasser
aitnasser

Reputation: 1246

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:

Upvotes: 3

Related Questions