How To PreventDefault On ng-click In AngularJS

Here’s a handy AngularJS, trick which allows you to prevent default behavior on ng-click event.

All you need to do is pass the $event parameter to your function inside the ng-click.

<button ng-click="saveData($event)">Save</button>

And receive that parameter inside your function within your controller and preventDefault() method.

$scope.saveData = function($event) {
  $event.preventDefault();
}

Must Read: How To Show Validation Errors On Submit In Angularjs?

Show Validation Errors On Submit In Angularjs

While working on one of my client’s project, I was required to display validation errors when the users hit the submit button. By default, AngularJS comes with $submitted form state. Its default value is false. As soon as the user hits the submit button, it becomes true.

We can use this state to make sure that error is hidden while the user has not clicked the submit button.

myForm.$submitted && myForm.username.$error.required

Demo:

Note: This will work only with AngularJS 1.3 or higher

Quick Tip: Using Bootstrap Tooltip With AngularJs