angularjsHow can I use AngularJS to prevent default behavior?
AngularJS provides a few different ways to prevent default behavior.
- 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>
- 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>
- 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
More of Angularjs
- How can I become an Angular expert from a beginner level?
- How do I use Angular to zip files?
- How can I create an editable AngularJS application?
- How can I prevent XSS attacks when using AngularJS?
- How can I use an if else statement in AngularJS?
- How do I use the window.open function with AngularJS?
- How can I use Angular to zoom in and out of a div?
- How can I use an AngularJS XSS cheat sheet to protect my website from malicious attacks?
- How can I use AngularJS to determine when an event will occur?
- How do I use Angular Zone to run my code?
See more codes...