AngularJS ng-click directive

The ng-click directive in AngularJS

The AngularJS ng-click directive enables us to add customized behavior as an element is clicked.

For example, you may use the ngClick to show and hide the content of specified elements like a paragraph, a form, etc. as a button or link is clicked.

Syntax of using ng-click directive

This is how you may use the ng-click directive:

<button

ng-click="expression">

...

</button>

There, the button is an element that can be replaced by any other HTML element like a link, span, paragraph, div, etc. where you want to perform certain custom behavior as that element is clicked.

See the examples in the following section to learn more about the angular ngClick directive.

A demo of ng-click on button click event

In this example, the ng-click directive is executed on the click event of the button. Every time you click the button, the number of times the button is clicked is shown below:

angularjs ng-click

The Code:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css">
<body ng-app="">

<h1>A demo of ng-click</h1>

<button class="btn btn-danger" ng-click="clicked = clicked + 1" ng-init="clicked=0">Click here to execute ng-click</button>

<div>Click No: <b>{{clicked}<!--Remove this while  testting-->}</b></div>


</body>
</html>

You can see, the ng-click directive is placed inside the button element where a value is incremented for each click.

Using the ng-init directive, the clicked value is initially set as 0.

A demo of ng-click in AngularJS with a link

Following is a more visual example of using the ng-click attribute. In this demo, it is used in a link element along with ng-show and ng-hide directives.

As you click the link “Click the link to display content” the h2 heading will display. Upon clicking the adjacent button, “Hide Content”, the content will disappear:

angularjs ng-click link

The Code:

<div ng-app="">

  <p class="title">A demo of ng-click in link</p>

  <a href="#" class="linkcls" ng-click="displaycontent=true">Display Content</a>

  <button class="btn btn-success" ng-click="displaycontent=false">Hide Content</button>

 

  <div class="container">

    <p  ng-hide="displaycontent">Click the link to display content!</p>

    <h2 class="show-ele" ng-show="displaycontent">This is the content shown as you clicked the link!</h2>

  </div>

 

</div>

On the click event of the link, the ng-click executes and makes the displaycontent true. It will display the content in the h2 element mapped with the ng-show directive.