Hit enter after type your search item

AngularJS ng-click directive explained with 2 examples

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.

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:


 

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 for learning 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 button is clicked is shown below:

angularjs ng-click

See online demo and code

The Code:


 

You can see, the ng-click directive is placed inside the button element where a value is incremented for each click. By using the ng-init directive, the clicked value is set initially 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

See online demo and code

The Code:


 

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 which is mapped with the ng-show directive.

This div height required for enabling the sticky sidebar