In the AngularJS environment, we just saw how and where to write code. Let us know learn a step by step procedure to create your first AngularJS application.
Also Read: Angularjs Components
Any AngularJS application consists of following main parts:
- ng-app : The ng–app directive tells AngularJS that this is the root element of the AngularJS application. All AngularJS applications must have a root element. You can only have one ng–app directive in your HTML document. If more than one ng–app directive appears, the first appearance will be used.
- ng-model : The ngModel directive binds an input , select , textarea (or custom form control) to a property on the scope using NgModelController, which is created and exposed by this directive. ngModel is responsible for: Binding the view into the model, which other directives such as input , textarea or select require.
- ng-bind : The ng–bind directive tells AngularJS to replace the content of an HTML element with the value of a given variable, or expression.
Steps to create AngularJS Application:
Step 1 − Load framework
Being a pure JavaScript framework, It can be added using <Script> tag.
<script src=”https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js”></script>
Step 2 − Define AngularJS Application using ng-app directive
<div id=’content’ ng-app=” ” ng-controller=” “>
</div>
Step 3 − Define a model name using ng-model directive
<p>Enter your Name: <input type = “text” ng-model = “name”></p>
Step 4 − Bind the value of above model defined using ng-bind directive.
<p>Hello <span ng-bind = “name”></span>!</p>
Steps to run AngularJS Application
Use above mentioned three steps in an HTML page.
Application1JS.htm
<html>
<head> <title>AngularJS First Application</title> </head> <body> <h1>Sample Application</h1> <div ng-app = “”> <p>Enter your Name: <input type = “text” ng-model = “name”></p> <p>Hello <span ng-bind = “name”></span>!</p> </div> <script src = “https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js”></script> </body> </html> |
Output
Open Application1JS.htm in a web browser. Enter your name and see the result.
Sample ApplicationEnter your Name: Hello ! |
How AngularJS integrates with HTML
- ng-app directive indicates the start of AngularJS application.
- ng-model directive then creates a model variable named “name” which can be used with the html page and within the div having ng-app directive.
- ng-bind then uses the name model to be displayed in the html span tag whenever user input something in the text box.
- Closing</div> tag indicates the end of AngularJS application.