This is a followup to a previous post discussing a directive that supports native form resets. While that directive goes a long way for simplifying form resets with AngularJS, it does have a glaring shortcoming. What if a form utilizes multiple models? AngularJS makes no judgement about this and actually there can be various reasons for why that is beneficial.
The previous solution expected to have one and only one model. In fact it should throw an error if more than one model is passed. Here is the original code from the original reset directive.
To support multiple models in an updated directive lets first make a checklist for what would need to be updated.
Since the attribute string will be a list, the directive will be dealing with an array of models to iterate over for creating both the getter/setters and the master copies of each model. Also it will iterate over the setters to set the corresponding models to their master copy during a reset event.
And low and behold the result. It works! It would have been a bit awkward if it hadn't.
In the end there was nothing very tricky about it but it can be extremely useful.
NOTE: I borrowed the
The previous solution expected to have one and only one model. In fact it should throw an error if more than one model is passed. Here is the original code from the original reset directive.
To support multiple models in an updated directive lets first make a checklist for what would need to be updated.
- A string format to pass in multiple models through the form attribute
- Create getter/setters for each model
- Create a master copy of each model
- Set each model to its respective master copy when the reset event fires
HTML
attribute, it should include the format supported by lists contained in HTML
attributes, namely space separated (think CSS class attributes). This way either format will work if favored by a designer or a developer.Since the attribute string will be a list, the directive will be dealing with an array of models to iterate over for creating both the getter/setters and the master copies of each model. Also it will iterate over the setters to set the corresponding models to their master copy during a reset event.
And low and behold the result. It works! It would have been a bit awkward if it hadn't.
In the end there was nothing very tricky about it but it can be extremely useful.
NOTE: I borrowed the
map
function from the AngularJS source since IE 8 does not support Array.prototype.map. Once again the source code proves it's a great place to pick up some tips and tricks.