Thursday, August 15, 2013

AngularJS Missing Directives: Native Form Resets Part 2

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.
  • 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
The attribute string format is simple enough since there is an established format for specifying a list, namely comma separated. But since this list is also an 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.

21 comments:

  1. Your website is really cool and this is a great inspiring article. Much thanks to you such a great amount for sharing this sort of information.
    Visit us for Custom Printed Puma Sweat Jacket.

    ReplyDelete