An AngularJS application is divided into two parts:
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.
For bindings we use two important attributes:
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 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.
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.
- In line 8, I have defined the ng-app attribute on div element.
- In line 9, I have defined the ng-model on input textbox control.
- In line 10, I have defined the ng-bind on span element.
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.