ng-click – Handling button clicks in AngularJS

Loading

ng-click is an AngularJS directive used to handle click events on HTML elements, typically buttons. It allows you to execute functions or expressions when a user clicks an element, making your web application interactive and dynamic.

Topics Covered:

  1. What is ng-click?
  2. Basic Syntax
  3. Executing a Function on Click
  4. Passing Parameters to Functions
  5. Using ng-click with Expressions
  6. Example: Incrementing a Counter
  7. Example: Toggling an Element’s Visibility
  8. Using ng-click with Conditional Logic
  9. Best Practices
  10. Conclusion

1. What is ng-click?

ng-click allows you to attach click event listeners to elements in AngularJS.
It executes an AngularJS expression or function when the element is clicked.
It is commonly used for buttons, links, divs, and other interactive elements.


2. Basic Syntax

<button ng-click="myFunction()">Click Me</button>
  • When the button is clicked, myFunction() is executed.

3. Executing a Function on Click

<button ng-click="sayHello()">Say Hello</button>
<p>{{message}}</p>
$scope.sayHello = function() {
$scope.message = "Hello, AngularJS!";
};
  • Clicking the button updates the message variable.

4. Passing Parameters to Functions

<button ng-click="greet('Narendra')">Greet</button>
<p>{{message}}</p>
$scope.greet = function(name) {
$scope.message = "Hello, " + name + "!";
};
  • Clicking the button updates message to “Hello, Narendra!”.

5. Using ng-click with Expressions

You can use inline expressions inside ng-click:

<button ng-click="count = count + 1">Increase Count</button>
<p>Count: {{count}}</p>
jsCopyEdit$scope.count = 0;
  • Each button click increments the counter.

6. Example: Incrementing a Counter

<button ng-click="increaseCounter()">Click Me</button>
<p>Clicked {{counter}} times</p>
$scope.counter = 0;
$scope.increaseCounter = function() {
$scope.counter++;
};
  • Each click increments the counter.

7. Example: Toggling an Element’s Visibility

<button ng-click="show = !show">Toggle</button>
<p ng-show="show">This is visible when toggled.</p>
$scope.show = false;
  • Clicking the button shows or hides the text.

8. Using ng-click with Conditional Logic

<button ng-click="login()">Login</button>
<button ng-click="logout()">Logout</button>
<p>{{message}}</p>
jsCopyEdit$scope.loggedIn = false;
$scope.login = function() {
    $scope.loggedIn = true;
    $scope.message = "You are logged in!";
};
$scope.logout = function() {
    $scope.loggedIn = false;
    $scope.message = "You are logged out!";
};
  • Clicking Login sets loggedIn = true, clicking Logout sets loggedIn = false.

Leave a Reply

Your email address will not be published. Required fields are marked *