Sunday, 10 May 2015

Interaction with HTML

In this example, it will give us a clear scenario of how Angular JS interacts with HTML tags.

Welcome.html:-
<!doctype html>
<html>
<head>
<script src="angular.js"></script>
</head>
<body ng-app="myapp">
<div ng-controller="HelloController" >
<h2>Welcome {{helloTo.title}} to the world of Web Programming!</h2>
</div>
<script src="Welcome.js"></script>
</body>
</html>

Welcome.js -
angular.module("myapp", [])
.controller("HelloController", function($scope) {
$scope.helloTo = {};
$scope.helloTo.title = "Everyone";
});


It is good programming practice to write the JavaScript Code in a separate file.


Screenshot:-


Explanation:-

To include Angular JS in the HTML file, we need to use "<script>" tag. Here, "angular.js" file is saved in the same folder where the HTML file is saved.

We need to tell what part of the HTML contains the Angular JS app. This done by adding the "ng-app"attribute to the root HTML element of the Angular JS app. You can either add it to html element or body element.

The "ng-controller" tells Angular JS what controller to use with the view. "helloTo.title" tells Angular JS to write the "model" value named "helloTo.title" to the HTML.

The  code written in "Welcome.js" registers a controller function named "HelloController" in the angular module named "myapp". The controller function is registered in angular via the "angular.module(...).controller(...)" function call.

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.

No comments:

Post a Comment