Skip to content

Instantly share code, notes, and snippets.

@kevineleven
Created April 10, 2016 14:34
Show Gist options
  • Save kevineleven/2afcceefb75e0554a2f4c53cb591053f to your computer and use it in GitHub Desktop.
Save kevineleven/2afcceefb75e0554a2f4c53cb591053f to your computer and use it in GitHub Desktop.
Cheatsheet for angular-formly

Formly Cheatsheet

Services

formlyConfig

Usage .factory(function(formlyConfig){formlyConfig.<property name>...})

Property name Type Default Description
disableWarnings boolean false Formly gives some useful warnings when you attempt to use a template that doesn't exist or there's a problem loading a template. You can disable these warnings via formlyConfigProvider.disableWarnings = true
disableNgModelAttrsManipulator boolean false Allows you to globally disable the ngModelAttrsManipulator which does a lot of magical things. I don't know why you'd want to disable it! But, all the power in the world to you!
ngModelAttrsManipulatorPreferUnbound boolean false This allows you to disable using ng- for maxlength. It is enabled by default because of this. I highly recommend you leave this off...
removeChromeAutoComplete boolean false Chrome broke autocomplete=""off"" (on purpose!). This will apply this hack to all of your forms. You can use removeChromeAutoComplete on the formly-form options property for a specific form. "
defaultHideDirective string 'ng-if' Allows you to control the directive used to hide fields. Common value for this might be ng-show. It will be passed !field.hide. You can also specify this on a form-by-form basis using the hide-directive attribute.
errorExistsAndShouldBeVisibleExpression depends undefined Allows you to control when errorExistsAndShouldBeVisible is set on the Field Configuration Object. Normally, this will default to being true if the field is invalid and $touched (or $dirty for angular 1.2), however, this allows you to override that behavior by simply assigning this to a Formly Expression which is evaluated like an expressionProperty (though it is synchronous and does not accept promises).
getFieldId function undefined You can override the field ID generation by specifying a function that is passed: (options, model, scope). Note: Remember to check options.id to make sure you don't override an ID that has been specified.
fieldTransform function undefined Allows you to modify/convert the fields before angular-formly handles them or validates them. So you can now have your own custom field configuration and then simply use this function to modify them into something that angular-formly recognizes, or you can dynamically add/remove/modify fields. It's a function that is called with the fields, model, formOptions, and form.
setType function undefined see table below
setWrapper function undefined see table below
templateManipulators function undefined see table below

formlyConfig.setType()

Option Data Type(s) Description
name string How you reference the type for a specific field.
template string Inlined template for the type. Can only be specified if there is no templateUrl
templateUrl string The URL for a template (uses the $templateCache). Can only be specified if there is no template.
defaultOptions object (must be valid field config) This will be merged with the options the user of the type provides (so they can override these options).
wrapper string,array of strings The name of a wrapper that has been registered with angular-formly
controller string (name),function Provides you the ability to add custom behavior to the type without having to make an entire directive (you can make a directive instead if you wish).
link function function(scope, el, attrs) Provides the ability to manipulate the DOM of the field
apiCheck object of functions angular-formly uses apiCheck for validating options. You can enforce the API to your type this way.
apiCheckInstance Instance of apiCheck Your own instance of apiCheck so you have the correct prefix/suffix/url/etc.
apiCheckFunction 'throw' or 'warn' Defaults to 'warn'. If you specify 'throw' then an error will be thrown instead of 'warn'
apiCheckOptions object The options to use when the check fails. Defaults to something sensible.
validateOptions function(options) Note: It is recommended that you use apiCheck with apiCheckInstance rather than validateOptions. This function will be invoked with the options of the field after it has been merged with it's optionsDefaults and any types that its type extends. Feel free to log warnings to the console or throw errors here to help users use your types correctly. Recommended: Use apiCheck.js as this is what formly uses and will already be available to you.

formlyConfig.setWrapper()

All template wrappers must follow these rules

  • Use in them to specify where the field template should be placed.
  • Have at least one, and only one of templateUrl or template
  • Not override another by name or type
Option Type Description
name string (required if no types are specified) The name of the wrapper that can be used by the wrapper property of a type or a field.
template string (mutually exclusive with templateUrl) The template to be used to wrap the field's template. Must contain
templateUrl string (mutually exclusive with template) A url to the template to be used to wrap the field's template. Must contain . Uses $templateCache to get the template, so you can safely preload the templates into the $templateCache.
types string,array of strings The name of types to which this wrapper should be applied
overwriteOk *same as setType above *same as setType above
apiCheck *same as setType above *same as setType above
apiCheckInstance *same as setType above *same as setType above
apiCheckFunction *same as setType above *same as setType above
apiCheckOptions *same as setType above *same as setType above
validateOptions *same as setType above *same as setType above

Allows you to manipulate the template of a specific field. This gives you a great deal of power without sacrificing performance by having bindings which you will never need as well as save repetition in your templates. A templateManipulator accepts the following arguments:

Argument Type Description
template string The template for the field. If you place this in the preWrapper pipeline, it will be simply the original template for the field. If you place this on the postWrapper pipeline, it will be the template for the field after all the wrappers have been applied.
options object The options for the field after all of the optionsDefaults have been applied.
scope object The $scope of the formly-field. See Custom Templates for information on what you'll find on this scope. It is NOT recommended that you manipulate the scope here! Use a controller for that.

template $scope properties

Property Name Description
options The data provided to configure the field. As a template author, if you need custom properties, you use the templateOptions property on this object. Note, there are a few things that get added to your field configuration (and hence, these options). One of these is "formControl" which can be used to display errors to the user (for example).
to Shortcut to options.templateOptions
fc Shortcut to options.formControl
showError Shortcut to options.validation.errorExistsAndShouldBeVisible
id The id of the field. You shouldn't have to use this.
index The index of the field the form is on (in ng-repeat)
form the form controller the field is in
model the model of the form (or the model specified by the field if it was specified).
fields all the fields for the form
formState The object passed as options.formState to the formly-form directive. Use this to share state between fields.

This service allows you to control what messages gets added to each field's validation.messages which can ultimately be used in an ng-messages context to great effect. It has a messages property which is what is used to attach the messages to the field's config. The messages here should be set as angular expressions (or functions) similar to how expressionProperties or validators works. You can always interact with messages on your own, but there are two helper methods in this service

Method Description
addTemplateOptionValueMessage

Directives

Attribute Scope Type Description
model = binding (required) The model to be represented by the form.
fields = binding (required) The field configurations for building the form. see Field Configuration Object below
form =? binding (optional) The variable to bind the NgFormController to.
options =? binding (optional) Options for the form.
root-el N/A See below for a description.
hide-directive N/A Allows you to control the directive used to hide fields. Common value for this might be ng-show. It will be passed !field.hide. You can also specify this on a global level using formlyConfig.extras.defaultHideDirective = 'ng-show'
track-by N/A Allows you to specify what you'd like the ng-repeat on the fields to track by. Example values: $index, field.key, vm.yourOwnFunction(field)
field-root-el N/A See below for a description.
formState N/A The formState property is passed to all formly-fields and is a mechanism for communicating between fields (without having to mess with your model).
resetModel N/A Calls resetModel on all fields
updateInitialValue N/A Calls updateInitialValue on all fields
templateManipulators N/A Template manipulators that will be applied to this form's fields
wrapper N/A Wrapper(s) that will be applied to this form's fields
fieldTransform function Just like the formlyConfig fieldTransform but scoped to just this instance of the form.
removeChromeAutoComplete N/A removeChromeAutoComplete: Chrome purposefully broke autocomplete="off" which really really stinks. Specify this option as true to fix this and remove the browser's ugly autocomplete from your form. You can also configure this globally using formlyConfig. Uses this hack
data N/A This is an object. Put whatever you want here.
root-el N/A You will not likely use this often (unless you have to support IE8, which is why it's a good idea to make your own directive that uses formly-form). The value given will control what is used for the formly-form's root element. It defaults to an ng-form, but if you want it to use a form or a div then you would specify root-el="form" or root-el="div" (respectively). If you choose anything except a form or ng-form, make sure to wrap it in your own ng-form or form and provide that with a name. Then pass that name to the form attribute so all the formControls of the fields will have somewhere to be added to.
field-root-el N/A This is similar to the root-el attribute which gives you control over the tag used in the formly-form template. This one however gives you control over the formly-field element. By default it is a div, but you can change it with the value specified in field-root-el.
Property Type Description
type string The type of field to be rendered. This is the recommended method for defining fields. Types must be pre-defined using formlyConfig.
template string,function The type of field to be rendered. This is the recommended method for defining fields. Types must be pre-defined using formlyConfig. note: with noFormControl property, can be used to add html instead of a form field
templateUrl string,function Can be set instead of type or template to use a custom html template form field. Works just like a directive templateUrl and uses the $templateCache If a function is passed, it is invoked with the field configuration object and can return either a string for the templateUrl or a promise that resolves to a string.
key string By default form models are keyed by location in the form array, you can override this by specifying a key.
defaultValue any If using the model doesn't work to set default value, use defaultValue to initialize it the model. If this is provided and the value of the model at compile-time is undefined, then the value of the model will be assigned to defaultValue.
hide boolean Whether to hide the field. Defaults to false. If you wish this to be conditional, use hideExpression. See below. Uses ng-if.
hideExpression string,function This is similar to expressionProperties with a slight difference. You should (hopefully) never notice the difference with the most common use case. This is available due to limitations with expressionProperties and ng-if not working together very nicely.
model object,string By default, the model passed to the formly-field directive is the same as the model passed to the formly-form. However, if the field has a model specified, then it is used for that field (and that field only). In addition, a deep watch is added to the formly-field directive's scope to run the expressionProperties when the specified model changes. Note, the formly-form directive will allow you to specify a string which is an (almost) formly expression which allows you to define the model as relative to the scope of the form.
expressionProperties object An object where the key is a property to be set on the main field config and the value is an expression used to assign that property. The value is a formly expressions. The returned value is wrapped in $q.when so you can return a promise from your function :-)
className string You can specify your own class that will be applied to the formly-field directive (or ng-form of a fieldGroup).
id string (avoid) This allows you to specify the id of your field (which will be used for its name as well unless a name is provided). Note, you can also override the id generation code using the formlyConfig extra called getFieldId.
name string (avoid) If you wish to, you can specify a specific name for your ng-model. This is useful if you're posting the form to a server using techniques of yester-year.
data object This is reserved for the developer. You have our guarantee to be able to use this and not worry about future versions of formly overriding your usage and preventing you from upgrading :-)
templateOptions object This is reserved for the templates. Any template-specific options go in here. Look at your specific template implementation to know the options required for this.
templateManipulators object Allows you to specify custom template manipulators for this specific field. (use defaultOptions in a type configuration if you want it to apply to all fields of a certain type).
preWrapper array of fns
postWrapper array of fns
wrapper string,array of strings This makes reference to setWrapper in formlyConfig. It is expected to be the name of the wrapper. If given an array, the formly field template will be wrapped by the first wrapper, then the second, then the third, etc. You can also specify these as part of a type (which is the recommended approach). Specifying this property will override the wrappers for the type for this field.
ngModelAttrs object This is part of the built-in formlyConfig templateManipulator called ngModelAttrsTemplateManipulator. This allows you to keep your templates very small and add custom behavior on at the type or field level. This is used by ngModelAttrsTemplateManipulator to automatically add attributes to the ng-model element of field templates. You will likely not use this often. This object is a little complex, but extremely powerful. It's best to explain this api via an example. For more information, see the guide on ngModelAttrs.
controller controller name function
link function This allows you to specify a link function. It is invoked after your template has finished compiling. You are passed the normal arguments for a normal link function.
optionsTypes string,array of strings Allows you to specify extra types to get options from. Duplicate options are overridden in later priority (index 1 will override index 0 properties). Also, these are applied after the type's defaultOptions and hence will override any duplicates of those properties as well.
modelOptions object Allows you to take advantage of ng-model-options directive. Formly's built-in templateManipulator (see below) will add this attribute to your ng-model element automatically if this property exists. Note, if you use the getter/setter option, formly's templateManipulator will change the value of ng-model to options.value which is a getterSetter that formly adds to field options. For more information on ng-model-options, see this ng-conf talk and these egghead lessons.
noFormControl boolean Used to tell angular-formly to not attempt to add the formControl property to your object. This is useful for things like validation, but not necessary if your "field" doesn't use ng-model (if it's just a horizontal line for example). Defaults to undefined.
watcher object,array of watches An object which has at least two properties called expression and listener. The watch.expression is added to the formly-form directive's scope (to allow it to run even when hide is true). You can specify a type ($watchCollection or $watchGroup) via the watcher.type property (defaults to $watch) and whether you want it to be a deep watch via the watcher.deep property (defaults to false).
formControl NgModelController This is the NgModelController for the field. It provides you with awesome stuff like $errors :-)
initialValue any Used in combination with resetModel and updateInitialValue. Basically, this is set to the value this field represents at compile time, or the last time updateInitialValue is called.
resetModel function Will reset the field's model and the field control to the last initialValue. This is used by the formly-form's options.resetModel function.
updateInitialValue function Will reset the field's initialValue to the current state of the model. Useful if you load the model asynchronously. Invoke this when the model gets set. This is used by the formly-form's options.updateInitialValue function.
runExpressions function It is not likely that you'll ever want to invoke this function. It simply runs the expressionProperties expressions. It is used internally and you shouldn't have to use it, but you can if you want to, and any breaking changes to the way it works will result in a major version change, so you can rely on its api.
value getter/setter function This is a getter/setter function for the value that your field is representing. Useful when using getterSetter: true in the modelOptions (in fact, if you don't disable the ngModelAttrsTemplateManipulator that comes built-in with formly, it will automagically change your field's ng-model attribute to use options.value.
validators object An object where the keys are the name of the validator and the values are Formly Expressions. All function validators can return true/false/Promise. A validator passes if it returns true or a promise that is resolved. A validator fails if it returns false or a promise that is rejected.
validation object (properties below) An object with a few useful properties mostly handy when used in combination with ng-messages
validation.messages object of name:expressions A map of Formly Expressions mapped to message names. This is really useful when you're using ng-messages like in this example.
validation.show boolean A boolean you as the developer can set to specify to force options.validation.errorExistsAndShouldBeVisible to be set to true when there are $errors. This is useful when you're trying to call the user's attention to some fields for some reason. See this example
validation.errorExistsAndShouldBeVisible boolean This is set by angular-formly. This is a boolean indicating whether an error message should be shown. Because you generally only want to show error messages when the user has interacted with a specific field, this value is set to true based on this rule: field invalid && (field touched

Below is the list of properties available in a fieldGroup field. They are the same as the property in the Field Configuration Object unless otherwise noted. One other important note is that because the fieldGroup is essentially another formly-form, it also inherit's (most of) the parent form's attributes (like root-el).

  • className
  • hide
  • hideExpression
  • model
  • key (based on the field's model)
  • elementAttributes
  • options (same as in formly-form)
  • form (attached to the object by angular-formly)

Can go in 4 places: field $watch expressionProperties validators messages

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment