AngularJS is a popular JavaScript framework for building dynamic web applications. In this tutorial, we will learn how to use AngularJS to create a simple application that compares two numbers and displays the greater number.
- Setting up AngularJS
First, you need to include AngularJS in your HTML file. You can do this by adding the following script tag to the head section of your HTML file:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
- Creating the AngularJS Application
Next, you need to create an AngularJS module for your application. This can be done by adding the following code to a script tag in the head section of your HTML file:
<script>
var app = angular.module('greaterNumberApp', []);
</script>
- Creating the Controller
Now, you need to create a controller for your application. Controllers are used to define the behavior of the application. Add the following code to a script tag in the head section of your HTML file:
<script>
app.controller('greaterNumberController', function($scope) {
$scope.number1 = 0;
$scope.number2 = 0;
$scope.findGreaterNumber = function() {
$scope.greaterNumber = Math.max($scope.number1, $scope.number2);
};
});
</script>
In this code, we have defined a controller named greaterNumberController
with two scope variables number1
and number2
. We have also defined a function findGreaterNumber
which calculates the greater number using the Math.max
function and assigns it to the scope variable greaterNumber
.
- Creating the HTML
Now, you need to create the HTML elements for the user interface. Add the following code to the body section of your HTML file:
<div ng-app="greaterNumberApp" ng-controller="greaterNumberController">
<input type="number" ng-model="number1" placeholder="Enter number 1">
<input type="number" ng-model="number2" placeholder="Enter number 2">
<button ng-click="findGreaterNumber()">Find Greater Number</button>
<p ng-if="greaterNumber !== undefined">The greater number is {{ greaterNumber }}</p>
</div>
In this code, we have used AngularJS directives like ng-app
, ng-controller
, ng-model
, and ng-click
to bind the controller with the HTML elements and handle user input and click events.
- Testing the Application
Now you can open your HTML file in a web browser and test the application. Enter two numbers in the input fields and click the "Find Greater Number" button. The application should display the greater number below the button.
Congratulations! You have successfully created a simple AngularJS application that compares two numbers and displays the greater number. You can further enhance this application by adding more features like error handling, validation, and styling. Happy coding!