Hello World Sample Application – AngularJS

An AngularJS application is divided into two parts:

  1. Application
  2. Bindings

AngularJS Application

An AngularJS application defines the section of HTML that starts the AngularJS application. We define the application using the ng-app attribute. You can add this attribute with any HTML element like body, div, table.

<body>
	<div ng-app>
	</div>
	<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script>
</body>

In the above code, we defined the ng-app attribute in the div section. AngularJS app now works with div and all the child controls of div section.


AngularJS Bindings

For bindings we use two important attributes:

  1. ng-model
  2. ng-bind

ng-model

ng-model denotes two way binding. We use this attribute with input controls like textboxes, select list, checkboxes etc.


<input type="text" ng-model="firstName" />

In the above code, we bind the input textbox with the firstName variable. AngularJS automatically create the model for the page with firstName as its variable. Whatever we made changes into the textbox it automatically apply into “firstName” variable.

ng-bind

ng-bind is used for one way binding. We use this attribute for showing data in HTML page. We can use this attribute with any HTML element.


<span ng-bind="firstName"></span>

Sample Application

We are creating the sample application using the above AngularJS attributes.


<!DOCTYPE html>
<html>
	<head>
		<title>First AngularJS App</title>
	</head>
<body>
	<div ng-app>
		<span>Enter your name:</span> <input type="text" ng-model="firstName" />
		<div> Hello <span ng-bind="firstName"></span></div>
	</div>
	<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script>
</body>
</html>

I will explain the above code in below points.

  1. In line 8, I have defined the ng-app attribute on div element.
  2. In line 9, I have defined the ng-model on input textbox control.
  3. In line 10, I have defined the ng-bind on span element.
  4. In line 12, I have included the AngularJS javascript in script tag.

From the above code, AngularJS creates an application and model. Initialize the firstName variable within the model and bind the firstName variable with the input and span controls.

Whanever you type text in input control, it automatically reflects in the span control.

Result

AngularJS_Sample_Application_UI