AngularJS Events

AngularJS Events

HTML events occur when a user interacts with a webpage, such as clicking or typing.

AngularJS provides specialized directives to easily capture and handle these events.


Event Directives

Instead of writing plain Javascript onclick events, you use ng-click.

AngularJS provides directives for almost every major DOM event available.

These include ng-change, ng-mouseover, ng-mouseenter, and ng-keydown.


Handling the Event

When an event directive triggers, it executes an AngularJS expression.

Most commonly, you will use this expression to call a function defined in your Controller.

This directly links user interactions to your powerful background JavaScript logic!

Event Example:

<div ng-app="myApp" ng-controller="myCtrl">
  <h1>Click Count: {{ count }}</h1>
  

<!-- Executes the expression when the button is clicked --> <button ng-click="count = count + 1">Increase Count</button> </div>

<script> var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { $scope.count = 0; }); </script>


SEO and Best Practices

Highly interactive pages reduce bounce rates, signaling page quality to search engines.

Avoid using heavy event listeners (like ng-mousemove) unnecessarily, as they can hurt performance.

Always prefer declarative event bindings in HTML to keep your application logic extremely readable.


Exercise 1 of 1

?

Which AngularJS directive is used to capture a mouse click on a button?