Friday, August 9, 2013

AngularJS Missing Directives: Native Form Resets

If you haven't played around with AngularJS yet, I highly advise you give it a try. There are plenty of introductory articles and videos out there that will whet your appetite and get you up and running (here, here and here to name a few). Go ahead, go play. This post will still be here later when you need it. And you will need it.

Okay, for everyone else, after the excitement and wonderment of two-way binding begins to wane you will start to notice some of the peculiarities about AngularJS. And then after that you will start to wonder why it doesn't do some of the things you would expect to it to do (the simple answer is generally the great dev team working on AngularJS hasn't gotten around to it yet). I refer to these missing functionalities as missing directives. Which means we can write our own directives to add any desired functionality!

Lets jump in and take a look at form resets. If you have been developing for the web for any period of time you know that there is a native INPUT element type that will reset all form input elements (including selects, textareas, etc.) to their original values. The following fiddle has a simple form that includes a native reset button and an Angular controller to initialize the model ("myModel").

Try editing the fields and hitting reset.

Wait. What happened? The expected behavior is for the form to reset the values of the input fields ('foo' and 'bar') to their original values ('Boop' and 'Beep' respectively). But as you can see this does not happen. What gives?

First, two underlying points:

  1. Since AngularJS forms do not use the value attribute to specify original values for forms, the native form elements therefore have no initial values outside of the AngularJS world.
  2. AngularJS forms do not understand which model is being used to manage the two-way binding for the input fields (this example uses 'myModel').

Second, you might be wondering why this is how AngularJS behaves. I did and so at a recent AngularJS meetup I asked Igor Minar, a core Google Angular developer, why it hadn't been implemented and he responded that the team just hadn't done it yet.

So, that leads to the question of what would be needed to make it work. Interestingly enough it's not a difficult thing to do once you have a firm understanding of AngularJS and its concept of directives. If you don't know what a directive is, this should be a good example.

Based on the points mentioned above, the directive would need to be:
  • aware of which model is represented by the form
  • what the original input element values are (the original state of the model)
  • capturing the native form reset event and preventing it from reseting the inputs to no values
  • restoring the original values to the form input elements from the model on the form reset event

Since directives can be attributes of an element, the directive can be an attribute of the form element itself similar to the ngSubmit directive. We then can use the attribute value to pass in the model for the form. This placement will also allow the capture of the native form reset event.

Lets preview with the finished directive before we dissect it. Once again, edit the form and hit the reset button.

Whew! It works.

If you notice on the HTML tab, the directive is invoked by applying an attribute to the form element with the value set to the model. The directive is then called and executes the returned function.

From the JavaScript tab we can see how the directive accomplishes our goals.

But first, some background on some of the key pieces used in the directive:

  • $parse - since you can't pass the model object itself through the attribute (at least without creating an isolated scope), you can use this handy dandy service to get the model object from the attribute value string
  • angular.copy - creates a deep copy of an object or an array
  • scope.$apply - executes the model assignment in an AngularJS context
  • $setPristine - used for setting the form to a 'pristine' state indication

We can see the first thing the directive linking function does is to create a getter/setter for the passed model and then it creates a deep copy of this model. This deep copy will be the value that the model is reset to on any form reset events. Since $parse will only return an object with method assign if it is a model, we can use that to error check the input from the attribute.

The next step binds the custom reset handler to the native form reset event. When the native form reset event is fired, the custom reset handler prevents the default action (resetting the input elements to their non-existent value attributes), sets the model to the original copied state and finally updates the form state to indicate it is pristine.

That's it. That's all it takes. Nothing more. If you haven't realized it yet, while two-way binding is magical, directives are the building blocks of AngularJS.


  1. This is such a good post. One of the best posts that I\'ve read in my whole life. I am so happy that you chose this day to give me this. Please, continue to give me such valuable posts. Cheers!

    ReactJS Online Training

  2. Because nowadays every business needs a huge support of Digital Marketing. Many people are searching a best products in internet, so to show our product as best in particular industry we need Digital Marketing.
    ExcelR Digital Marketing Courses In Bangalore

  3. You should take part in a contest for one of the greatest websites on the web. I'm going to highly recommend this blog!


  4. This post is really nice and informative. The explanation given is really comprehensive and informative. I also want to say about the digital marketing online training


  5. Thanks for your extraordinary blog. Your idea for this was so brilliant. This would provide people with an excellent tally resource from someone who has experienced such issues. You would be coming at the subject from a different angle and people would appreciate your honesty and frankness. Good luck for your next blog!
    Tally ERP 9 Training
    tally classes
    Tally Training institute in Chennai
    Tally course in Chennai
    seo training classes
    seo training course
    seo training institute in chennai
    seo training institutes
    seo courses in chennai
    seo institutes in chennai
    seo classes in chennai
    seo training center in chennai

  6. I really appreciate your method to explaining, I hope to see more posts from your blog. thank you!
    Digital Marketing Course In Kolkata
    Web Design Course In Kolkata
    SEO Course In Kolkata

  7. Excellent Blog! I would like to thank for the efforts you have made in writing this ExcelR Digital Marketing Course Pune post. I am hoping the same best work from you in the future as well. I wanted to thank you for this websites! Thanks for sharing. Great websites!

  8. Way cool! Some very valid points! I appreciate you writing this write-up plus the rest of the site develop is also very good.

  9. Hi there! I just want to give you a big thumbs up for your great info you have got here on this post. I am returning to your press web site for more soon.

  10. Welcome to the party of my life here you will learn everything about me.
    Digital Marketing Course Pune


  11. You have clarified the idea truly well. Was searching for this data from some time and fortunately I discovered your post. Searching forward for a greater amount of such useful updates from you
    Data Science Training In Hyderabad
    Data Science Course In Hyderabad

  12. This is an awesome motivating article. I am practically satisfied with your great work. You put truly extremely supportive data. Keep it up. Continue blogging. Hoping to be perusing your next post
    Courses in Digital Marketing in Pune

  13. It's very nice to find out other writers share like minds on some content. This is the case with your article. I really enjoyed this.
    Best Data Science training in Mumbai

    Data Science training in Mumbai

  14. Very interesting article with great useful information. Java training in chennai I am also sharing this article with my friends you have written excellent content. Thanks for sharing this kind of informative blog about Java.
    Java training in chennai | Java training in annanagar | Java training in omr | Java training in porur | Java training in tambaram | Java training in velachery

  15. Great Content, For training in Angularjs do visit GoLogica
    AngularJS Trainings

  16. I wondered upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I’ll be subscribing to your feed and I hope you post again soon

    Dot Net Training in Chennai | Dot Net Training in anna nagar | Dot Net Training in omr | Dot Net Training in porur | Dot Net Training in tambaram | Dot Net Training in velachery

  17. Nice blog Post ! This post contains very informative and knowledgeable. Thanks for sharing the most valuable information.
    Data Science Training in Hyderabad

  18. This blog is truly useful to convey overhauled instructive undertakings over web which is truly examination. I discovered one fruitful case of this truth through this blog. I will utilize such data now.
    Digital Marketing Course In Hindi

  19. Great blog I must say thanks for such a good Information that you shared with us. I appreciate your efforts and Looking forward for more blogs like this.
    IELTS Coaching in chennai

    German Classes in Chennai

    GRE Coaching Classes in Chennai

    TOEFL Coaching in Chennai

    spoken english classes in chennai | Communication training

  20. Thank you so much for this incredible guide. This has given me so much information
    AI Training in Hyderabad

  21. Good post and informative. Thank you very much for sharing this good article, it was so good to read and useful to improve my knowledge as updated, keep blogging.Thank you for sharing wonderful information with us to get some idea about that content.
    oracle training in chennai

    oracle training institute in chennai

    oracle training in bangalore

    oracle training in hyderabad

    oracle training

    oracle online training

    hadoop training in chennai

    hadoop training in bangalore

  22. Nice post. Thanks for sharing! I want people to know just how good this information is in your article. It’s interesting content and Great work.Very useful and informative content has been shared out here, Thanks for sharing it

    Azure Training in Chennai

    Azure Training in Bangalore

    Azure Training in Hyderabad

    Azure Training in Pune

    Azure Training | microsoft azure certification | Azure Online Training Course

    Azure Online Training

  23. Excellent Blog! I would Thanks for sharing this wonderful content.its very useful to us.This is incredible,I feel really happy to have seen your webpage.I gained many unknown information, the way you have clearly explained is really fantastic.keep posting link this information.
    Full Stack Training in Chennai

    Full Stack Course Chennai
    Full Stack Training in Bangalore

    Full Stack Course in Bangalore

    Full Stack Training in Hyderabad

    Full Stack Course in Hyderabad

    Full Stack Training

    Full Stack Course

    Full Stack Online Training

    Full Stack Online Course

  24. I really loved reading your blog. I also found your posts very interesting. In fact, after reading, I had to go show it to my friend and he enjoyed it as well!!!!
    Machine Learning Training in Hyderabad
    Machine Learning Course in Hyderabad

  25. Highly informative article. This site has lots of information and it is useful for us. Thanks for sharing your views.
    Data Science Training in Hyderabad
    Data Science Course in Hyderabad

  26. I would like to thank you for the efforts taken to write this wonderful blog.
    Data Analytics Course Online 360DigiTMG

  27. From the examples given above, you must have realized that technology is everywhere. Do you know how Netflix knows the movies and shows you might like? Well, it is all because of data science. data science course in hyderabad

  28. It uses machine learning algorithms and approaches to understand the requirements of yours and helps you by being one step ahead of you. data science course in hyderabad

  29. I am highly overwhelmed to read this perfect piece of writing. It has really enthused me to read more on this topic.
    Data Science training in Mumbai
    Data Science course in Mumbai
    SAP training in Mumbai

  30. This article is well formulated. I particularly like the way how you have delivered all the major points about the topic of the content in petite and crisp points.
    SAP training in Kolkata
    SAP training Kolkata
    Best SAP training in Kolkata
    SAP course in Kolkata


  31. it’s really nice and meanful. it’s really cool blog. Linking is very useful have really helped lots of people who visit blog and provide them usefull information.
    Data Science Training in Hyderabad

    I am really happy to say it’s an interesting post to read . I learn new information from your article , you are doing a great job . Keep it up

    Devops Training in USA

    Hadoop Training in Hyderabad

    Python Training in Hyderabad

  32. Such an excellent article. Found very interesting and resourceful, I would like to thank you for the efforts you had made for writing this awesome article.
    typeerror nonetype object is not subscriptable

  33. I will very much appreciate the writer's choice for choosing this excellent article suitable for my topic. Here is a detailed description of the topic of the article that helped me the most.
    unindent does not match any outer indentation level

  34. I'm glad I found this blog! Occasionally, students want to know the keys to writing productive literary essays. Your first-class knowledge of this great job can become a suitable foundation for these people. Good
    unindent does not match any outer indentation level python

  35. Tremendous blog quite easy to grasp the subject since the content is very simple to understand. Obviously, this helps the participants to engage themselves in to the subject without much difficulty. Hope you further educate the readers in the same manner and keep sharing the content as always you do.

    Data Science certification in Raipur

  36. Nice Information Your first-class knowledge of this great job can become a suitable foundation for these people. I did some research on the subject and found that almost everyone will agree with your blog.
    Cyber Security Course in Bangalore

  37. Writing in style and getting good compliments on the article is hard enough, to be honest, but you did it so calmly and with such a great feeling and got the job done. This item is owned with style and I give it a nice compliment. Better!
    Cyber Security Training in Bangalore