Introduction
In my previous article I told you about:
- How to Show Alert Box in AngularJS.
- ng-init and ng-repeat Directive in AngularJS
In this article I will tell you about the ng-click and ng-blur directives in AngularJS.
Step 1
First of all you need to add an external Angular.js file to your application, for this you can go to the AngularJS official site or can download my source code and then can fetch it or you can click on this link and download it: ANGULARJS.
After downloading the external file you now need to add this file to the Head section of your application as in the following:
<head runat="server">
<script src="angular.min.js"></script>
<title></title>
</head>
Step 2
First I will work on the click functionality of a button. Write this code in the Body section of your application:
<div>
<h2>You have clicked the Button: {{click}} Times</h2>
<button ng-click="click=click+1" ng-init="click=0" >Increment</button>
</div>
I will create a click counter that will work on the click of a button; for that I took a button and a label in a Div.
In the button you can see that I had first provided the initial value in the init that is set to "0", in the button ng-click is also used that will increment the value of click by 1 on each new click.
The value of the click counter is provided in the H2 tag, in the H2 tag you can see that I bound it with the click using {{}}.
Now if we run our application than first 0 will be shown by the H2 tag:
Now if I click on the Button than you will see that the value is regularly incremented by 1.
In the next steps I will show you how to use the ng-blur directive of AngularJS.
Step 3
I will again create a click counter but this time it will work on ng-blur() and not on ng-click(). Since I am showing the Blur() the best way of showing is using a TextBox. I took two Textboxes but ng-blur will be applied to the first TextBox only.
<div style="border:1px dotted">
<input ng-blur="leave=leave+1" ng-init="leave=0" />
<input id="text2" />
<h2>You have left Textbox: {{leave}} Times</h2>
</div>
Here again I had passed some initial value through the init, this value will be incremented by one on blur.
Now if we run our application then first 0 will be shown by the H2 tag:
As the first TextBox looses it's focus you can see that the counter starts incrementing by 1.
The complete code is as follows:
<html ng-app xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script src="angular.min.js"></script>
<title></title>
</head>
<body>
<div>
<h2>You have clicked the Button: {{click}} Times</h2>
<button ng-click="click=click+1" ng-init="click=0" >Increment</button>
</div>
<br />
<div style="border:1px dotted">
<input ng-blur="leave=leave+1" ng-init="leave=0" />
<input id="text2" />
<h2>You have left Textbox: {{leave}} Times</h2>
</div>
ใใ</body>
<body>
</body>
</html>