If you are a visual learner take a look at the video below which covers the topics outlined in the post
In this AngularJS Tutorial we will see two techniques to prevent the data submission in case of error. Both can live together in the same form to create a more robust code.
The ng-submit way
In this case we want that Angular evaluates a condition and then decide if to call or not the function
In the code above you can see at line 4 that the ng-submit parameter is a function (submitForm) belonging to the eventCtl contoller (in this case we referece the controller with an alias because we are using the “Controller as” syntax).
Instead, in the code below, at line 4 we change the expression by adding a boolean value (addEventForm.$valid) chained to the function with the && (AND) operator: this force Angular to call the function only if the first value is true. As you can guess the addEventForm.$valid property is true if there are NO validation issues otherwise is false.
Disabling the button
The ng-submit techniques works but can create a little confusion. Think about a user that fills the form generating some issues and then clicks the submit button: nothing happens because the form is not valid and there is no submission, but the user has clicked the button and he has no response to his action. What we are doing now is disabling the submit button if the form is not valid.
Take a look at the code below at line 13. There is a ng-disable directive that evaluates the addEventForm.$invalid property that is true when ther are errors in the form. The result is that the submit button is disabled in case of validation issues and the user is guided without misunderstandings towards the resolution of the problems of validation.
Subscribe to our newswletter to obtain an extra discount on the full price on the video tutorial
This post is taken from our complete course AngularJS for the Real World – Learn by creating a WebApp. Take a look and give us a feedback!