Open In App

AngularJS ng-click Directive

Last Updated : 01 Aug, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

The ng-click Directive in AngluarJS is used to apply custom behavior when an element is clicked. It can be used to show/hide some element or it can pop up an alert when the button is clicked. 

Syntax:

<element ng-click="expression"> 
    Contents... 
</element>

Parameter Value:

  • expression: It specifies when the particular element is clicked then the specific expression will be evaluated.

Supported tag: It is supported by all the elements in HTML.

Example 1: This example illustrates the implementation of the ng-click Directive to display an alert message after clicking the element. 

HTML
<!DOCTYPE html>
<html>

<head>
    <title>ng-click Directive</title>
    <script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
    </script>
</head>

<body ng-app="geek" 
      style="text-align:center">
    <h1 style="color:green">
        GeeksforGeeks
    </h1>
    <h2>ng-click Directive</h2>
    <div ng-controller="app">
        <button> 
            <a href="" 
               ng-click="alert()">
                    Click Here
            </a> 
        </button>
    </div>
    <script>
        var app = angular.module("geek", []);
        app.controller('app', ['$scope', function($app) {
            $app.alert = function() {
                alert("This is an example of ng-click");
            }
        }]);
    </script>
</body>
</html>

Output:

ng-click Directive

Example 2: This example illustrates the implementation of the ng-click Directive to display some content after clicking the element. 

HTML
<!DOCTYPE html>
<html>

<head>
    <title>ng-click Directive</title>
    <script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
    </script>
</head>

<body ng-app="" 
      style="text-align:center">
    <h1 style="color:green">
        GeeksforGeeks
    </h1>
    <h2>ng-click Directive</h2>
    <form name="form">
        <div ng-hide="isShow">
            Enter Name:
            <input type="text" required 
                   ng-model="Name" />
            <br><br>
            <input type="button" 
                   ng-disabled="form.$invalid" 
                   ng-click="isShow = true" 
                   value="Sign in" />
        </div>
        <div ng-show="isShow">
            Sign in successful.<br>
            <input type="button" 
                   ng-click="isShow = false;Name=''" 
                   value="Logout" /> 
        </div>
    </form>
</body>
</html>

Output:

ng-click Directive

Next Article

Similar Reads