Step 8-AngularJS Event

Definition- AngularJS allows you to handle events, such as mouse clicks, button presses, and key presses, using directives. Directives are special attributes that you can add to HTML elements to bind behavior to them. AngularJS provides several built-in directives for handling events, such as ng-click and ng-keypress.

Types of Events-

AngularJS EventUsageCode Snippet
ng-clickHandles the click event on an element.<button ng-click="doSomething()">Click me</button>
ng-blurHandles the blur event when an element loses focus.<input type="text" ng-blur="doSomething()">
ng-changeHandles the change event when the value of an input, select or textarea element changes.<input type="text" ng-change="doSomething()">
ng-submitHandles the submit event when a form is submitted.<form ng-submit="submitForm()">...</form>
ng-keydownHandles the keydown event when a key is pressed down on an element.<input type="text" ng-keydown="doSomething($event)">
ng-mousedownHandles the mousedown event when the mouse button is pressed down on an element.<div ng-mousedown="doSomething()">...</div>
ng-mouseupHandles the mouseup event when the mouse button is released on an element.<div ng-mouseup="doSomething()">...</div>
ng-mouseenterHandles the mouseenter event when the mouse enters an element.<div ng-mouseenter="doSomething()">...</div>
ng-mouseleaveHandles the mouseleave event when the mouse leaves an element.<div ng-mouseleave="doSomething()">...</div>

Now look on code example –

<!DOCTYPE html>
<html>
<head>
  <title>AngularJS Event Example</title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body ng-app="">
  <button ng-click="myFunction($event)">Click me!</button>
  <p ng-show="clicked">Button was clicked!</p>

  <script>
    function MyController($scope) {
      $scope.clicked = false;

      $scope.myFunction = function(event) {
        $scope.clicked = true;
        event.preventDefault();
      };
    }
  </script>

  <div ng-controller="MyController">
    {{message}}
  </div>
</body>
</html>

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.