Introduction:

In this article we will explain how to use ng-click directive in AngularJS Or what is use ng-click directive in AngularJS or how to call a function on button click using  ng-click in angularJS with example.

Description:

In AngularJS ng-click directive detect the click event to HTML elements like Button that accepts function name or statements to execute.

Let’s see an example of ng-click event in angularjs

 <!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="Scripts/angular.min.js"></script>
    <script src="Scripts/jquery-1.8.2.min.js"></script>
  
    <script>
        var app = angular.module("app", []);
        app.controller("MyClickController", function ($scope) {
            $scope.counter = 0;
            $scope.Increment = function () {
                $scope.counter += 1;
            }
        });
    </script>
 
 
</head>
<body>
    <div ng-app="app" ng-controller="MyClickController">
        <b>ng-click Event</b><br /><br />
        <button ng-click="Increment()">Increment</button>
        <p>Counter: {{ counter }}</p>
        <button ng-click="myCounter  = myCounter + 1">Counter </button>
        <div> Counter: {{ myCounter  }}</div>
    </div>
    </body>
</html>


Output:


In above code 1st HTML block we have a button whose ng-click is set to "Increment()” function defined in the controller. When the button is clicked, the value of the counter variable is incremented by "1" that gets written in the expression inside the <p> element.

In the 2nd block of code, on click of the button a dynamic  myCounter variable is created and its value is incremented by "1" that gets written in the expression inside the <div> element.

 

 I hope this article will help to you.

0 comments


Leave a comment

Make sure you enter the (*) required information where indicated. HTML code is not allowed.

Welcome to SQL Tutorials Point

Don't have an account? Click here to Create a new account, it takes less than a minute.