Angularjs Form Submission
The Task
- Create a form
- Add a submit button
- Form must submit on press of enter
- Cancel button exits form without save
- after submit the user returns to the page they were on prior to the form
My Tools
- PLENTY of other JS libraries that need not be mentioned here
Originally tried to have ng-submit on form with a submit button of type="submit" and a generic cancel button that called a cancel function from the scope. This is where I realized that the function called ng-submit is called even when the cancel button is pressed. So now the submit function needs to be aware that there is a button somewhere in the form that halts the form submission despite valid/invalid values in the form fields.
This prompted a googling binge that eventually led me to creating a custom submit directive. Using this Gist as a guide I implemented just that. This directive will catch the submission of a form event and take over. It removes pristine and adds the dirty class to preserve what would happen by default in a normal submission. Then the directive checks that the form is invalid. If it is then a notification describing what needs to be changed is displayed to the user. Then the directive evaluates the function that was passed in to the directive. All of this takes place in the directives link function so at the end scope.$apply() must be called to ensure we are in sync across any views.
No comments:
Post a Comment