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:
- What is
ng-click
? - Basic Syntax
- Executing a Function on Click
- Passing Parameters to Functions
- Using
ng-click
with Expressions - Example: Incrementing a Counter
- Example: Toggling an Element’s Visibility
- Using
ng-click
with Conditional Logic - Best Practices
- 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 setsloggedIn = false
.