Samples of ng-click, ng-disable, $watch in AngularJs

This sample shows the use of  ng-click, ng-disable, flag, $watch, ng-model binding in angularjs.

Scenario  :-  Create a page with two input type one for Name and other for Age. Also one button to increased age. Bind these input type using ng-model with default values as Name=”Test” , Age=20.

when click on increased button age should be increase till 26 and button should disabled. If Age input type value change with other value,it should change the state of increase button accordingly.

Solution:-

Create the Samples.html page with Name, Age input type with Increase age button as shown below.

Samples.html


<html ng-app="testApp">
<head>
<title></title>
</head>
<body>
<div ng-controller="SampleController">

<!-- Bind the text value using ng-model -->
Name:<input type="text" ng-model="Name" />
<br />
Age: <input type="text" ng-model="Age" />
<br />
Note: -
You Can increase Age till 26 .
<br />
<button ng-disabled="flag" ng-click="increaseAge()"> Increase Age </button>
</div>
<script src="Scripts/angular.min.js"></script>
<!-- Code to check the condition -->
<script>

var module = angular.module("testApp", []);
module.controller("SampleController", function ($scope) {
$scope.Name = "Test";
$scope.Age = 20;
$scope.increaseAge = function () {
if ($scope.Age != 26) {
$scope.Age++;
}
else {
$scope.flag = true;
}
};
$scope.$watch("Age", function () {
if ($scope.Age < 26) {
$scope.flag = false;
}
else {
$scope.flag = true;
}
});
});
</script>
</body>
</html>

After running the above code you will get the desired output as per the above mention scenario.

Output :-

Ng-Sample1
 

🙂 Happy Coding……….

Advertisements

One comment

  1. subhash20may · June 30, 2015

    Good explanation. Thanks

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s