In this first article on AngularJS, let’s build the traditional “hello world” application. For this simple AngularJS Hello World application, we will have an input field which allows users to type their name. Then we will take the user name and display user’s name along with the welcome message.
For building up an AngularJS application we need to include “angular.js” file and it can be included in 2 different ways.
- Go to angularjs.org site –> click on Download –> Copy the CDN URL and use it in the application.
- Download that angular.js file into your local folder and you can include it.
HelloWorld.html
<!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>HelloWorld Application</title> </head> <body ng-app=""> <input type="text" ng-model="username" placeholder="Enter your name"> <h2> Welcome <span ng-bind="username"></span>!!! </h2> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"> </script> </body> </html>
Simply copy paste the above code in any text editor and save it the extension of “.html”. Finally open the saved “HelloWorld.html” in your browser.
Output
Whatever we type in the textbox will get appended to the “Welcome” String dynamically.
How everything works ?
- The ng-app directive is added to the <body> tag. ng-app defines the starting point of the angular js application flow. I have not given any value to the ng-app, as of now leave it as such we will discuss more about it in my later articles. Just remember that it is a directive.
- We have an input tag, with a directive called ng-model on it. The ng-model directive can be used on any html element whenever we want to enter a data and want the value to be accessed through JavaScript. Here, we are telling AngularJS to store the value entered by the user in the text field to be stored in the variable “username”.
- We also have used another directive called ng-bind. ng-bind or double-curly {{}} brackets are almost the same,instead of using <span ng-bind=”username”></span>, we can use {{username}}. Both will give the same result only. Angular will be binding the model value here. The model used in the above line is “username” and the value entered by the user is “JavaInterviewPoint” , angularjs will place the value of the model in the place of ng-bind=”username”.
- That’s it we have built and executed our first AngularJS Hello World Example application.
Leave a Reply