Let us see how to set up AngularJS library to be used in web application development. It also briefly describes the directory structure and its contents.
When you open the link https://angularjs.org/, after clicking Download AngularJS you will see there are two options to download AngularJS library −
This screen gives various options of using Angular JS as follows −
We will be using the CDN versions of the library throughout the discussion.
Now let us write a simple example using AngularJS library. Let us create an HTML file myfirstexample.html shown as below −
<!doctype html> <html> <head> <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script> </head> <body ng-app = "myapp"> <div ng-controller = "HelloController" > <h2>Welcome {{helloTo.title}} to the world of Tutorialspoint!</h2> </div> <script> angular.module("myapp", []) .controller("HelloController", function($scope) { $scope.helloTo = {}; $scope.helloTo.title = "AngularJS"; }); </script> </body> </html>
Let us go through the above code in detail −
We include the AngularJS JavaScript file in the HTML page so that we can use it −
<head> <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"> </script> </head>
You can check the latest version of AngularJS on its official website.
Next, it is required to tell which part of HTML contains the AngularJS app. You can do this by adding the ng-app attribute to the root HTML element of the AngularJS app. You can either add it to the html element or the body element as shown below −
<body ng-app = "myapp"> </body>
The view is this part −
<div ng-controller = "HelloController" > <h2>Welcome {{helloTo.title}} to the world of Tutorialspoint!</h2> </div>
ng-controller tells AngularJS which controller to use with this view. helloTo.title tells AngularJS to write the model value named helloTo.title in HTML at this location.
The controller part is −
<script> angular.module("myapp", []) .controller("HelloController", function($scope) { $scope.helloTo = {}; $scope.helloTo.title = "AngularJS"; }); </script>
This code registers a controller function named HelloController in the angular module named myapp. We will study more about modules and controllers in their respective chapters. The controller function is registered in angular via the angular.module(…).controller(…) function call.
The $scope parameter model is passed to the controller function. The controller function adds a helloTo JavaScript object, and in that object it adds a title field.
Save the above code as myfirstexample.html and open it in any browser. You get to see the following output −
Welcome AngularJS to the world of Tutorialspoint!
What happens when the page is loaded in the browser ? Let us see −