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.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With