9951 explained code solutions for 126 technologies


angularjsHow can I use AngularJS to prevent default behavior?


AngularJS provides a few different ways to prevent default behavior.

  1. Using ng-click Directive:

ng-click directive allows us to prevent default behavior of an element. We can use $event.preventDefault() to prevent the default behavior.

For example:

<a href="www.example.com" ng-click="$event.preventDefault()">Link</a>
  1. Using $event Object:

We can also use $event object to prevent default behavior of an element. We can use $event.preventDefault() to prevent the default behavior.

For example:

<a href="www.example.com" ng-click="doSomething($event)">Link</a>

<script>
  $scope.doSomething = function($event) {
    $event.preventDefault();
  }
</script>
  1. Using $event.stopPropagation():

$event.stopPropagation() can be used to prevent event bubbling.

For example:

<div ng-click="doSomething($event)">
  <a href="www.example.com" ng-click="$event.stopPropagation()">Link</a>
</div>

<script>
  $scope.doSomething = function($event) {
    console.log('This will not be called');
  }
</script>

Helpful links

Edit this code on GitHub