Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 916
Slava Fomin II Avatar asked Dec 02 '25 07:12

Slava Fomin II


2 Answers

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:

like image 50
aitnasser Avatar answered Dec 05 '25 01:12

aitnasser


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.

like image 41
Slava Fomin II Avatar answered Dec 05 '25 02:12

Slava Fomin II



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!