First of all, what is AngularJS?
AngularJS is a JavaScript Framework, which is very powerful and its library is written in JavaScript. This framework is used to make single page applications. From this definition, you should get an idea that if we want to make a single page application, AngularJS is the answer as the most powerful JavaScript Framework. AngularJS extends HTML with the new attributes. AngularJS allows us to write the applications in a clean Model-View-Controller way.
EVENTS
When we create an advanced AngularJS Application, we will need to handle DOM events like mouse clicks, mouse moves, change events etc. AngularJS adds an event listener to HTML.
There are events in AngularJS also. They are called as AngularJS events directives.
Various AngularJS event directives are given below.
- ng-blur
- ng-change
- ng-click
- ng-copy
- ng-cut
- ng-dblclick
- ng-focus
- ng-keydown
- ng-keypress
- ng-keyup
- ng-mousedown
- ng-mouseenter
- ng-mouseleave
- ng-mousemove
- ng-mouseover
- ng-mouseup
- ng-paste
HTML events are not overridden by AngularJS events, but both are executed successfully.
Let’s understand one event with an example.
View
In this view, you can see that we have used click event, ng-click. ng-click will fire whenever we will click mouse button. It will provide the result, which we have written in controllers function clickHere().
You can see here that we have written a function in the controller to handle the click event. This will pop up an alert with text “Event clicked”. Let’s run this and see the output.
Now, if we click on “Click here”. We will get popup, as shown below.
Thus, you can see and understand from the example given above, how the events are handled in Angular JS.
Events are basically categorized into three main categories, which are shown below.
- Mouse Events
- Keyboard Events
- Change Events
Mouse Events,
- ng-click
- ng-dblclick
- ng-mousedown
- ng-mouseup
- ng-mouseenter
- ng-mouseleave
- ng-mousemove
- ng-mouseover
Keyboard Events,
- ng-keydown
- ng-keyup
- ng-keypress
If we need to know when an input element state changes due to the user interaction, we use ng-change directive.
$event Object
We pass $event object as an argument, when calling a function. The $event object contains the Browser’s event.
Let’s understand this with an example of finding the coordinates by passing $event to the function.
View
Script
You can see here above that we have passed $event in the function as a parameter function name: myFuncEvent. If we run this and check the output, it will give us the coordinates, while we move our mouse.
Output
You can use all the event directives, which are written above in your own examples. The events are added to any HTML element. If there is HTML event, which is defined previously. AngularJS event will not override it, but both the events will occur.
After going through this article, please provide your valuable feedback.