In this article I will explain with an example, how to fire click event for a Button using ng-click directive in AngularJS.
The AngularJS ng-click directive is used to assign click events to HTML elements like Button.
Implement Button click event using ng-click directive in AngularJS
The below HTML Markup consists of an HTML DIV to which ng-app and ng-controller AngularJS directives have been assigned.
The HTML DIV consists of an HTML Button assigned with ng-click AngularJS directive and an HTML SPAN specified with ng-bind AngularJS directive.
Note
: If you want to learn more about these directives please refer my article Introduction to AngularJS.
When the Button is clicked, the ButtonClick event handler (defined within the Controller) is called. Inside the ButtonClick event handler, the Message variable is set and its value is displayed in the HTML SPAN.
<
script
type
=”text/javascript”
src
=”https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js”></
script
>
<
script
type
=”text/javascript”>
var
app = angular.module(
‘MyApp’
, [])
app.controller(
‘MyController’
,
function
($scope) {
$scope.ButtonClick =
function
() {
$scope.Message =
“Button clicked.”
}
});
</
script
>
<
div
ng-app
=”MyApp”
ng-controller
=”MyController”>
<
input
type
=”button”
value
=”Click Me!”
ng-click
=”ButtonClick()”
/>
<
br
/>
<
br
/>
<
span
ng-bind
=”Message”></
span
>
</
div
>
Screenshot
Demo
Downloads
AngularJS_ng-click.zip