fastread homefastrread library fastread menu

AngularJS : Hello World

Tutorial by:Sumit Chauhan      Date: 2016-08-11 23:51:05

❰ Previous Next ❱

Here is a simple "hello world" example made with AngularJS which shows the model, view and controller parts of an AngularJS app:

<!DOCTYPE html>
<html lang="en">


<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
</head>

<body ng-app="myapp">


<div ng-controller="HelloController" >

    <h2>Hello {{helloTo.title}} !</h2>

</div>


<script>
angular.module("myapp", [])
    .controller("HelloController", function($scope) {
        $scope.helloTo = {};
        $scope.helloTo.title = "World, AngularJS";
    } );
</script>



</body>

</html>

In this example the "view" is this part:

<div ng-controller="HelloController" >

    <h2>Hello {{helloTo.title}} !</h2>

</div>

Notice the ng-controller attribute. This attribute tells AngularJS what controller to use with this view. Notice also the {{helloTo.title}} text. This is part of AngularJS's template system. This tells AngularJS to write the "model" value named helloTo.title to the HTML at this location.

The "controller" is this part:

<script>
angular.module("myapp", [])
    .controller("HelloController", function($scope) {
        $scope.helloTo = {};
        $scope.helloTo.title = "World, AngularJS";
    });
</script>

This code registers a controller function named "HelloController" in the angular module named "myapp". Angular modules will be explained later in this tutorial.

The $scope parameter passed to the controller function is the "model". The controller function adds a helloTo JavaScript object, and in that object it adds a title field. It is this helloTo.title value from the model which the view writes into the HTML

❰ Previous Next ❱