Tuesday, 4 November 2014

Introduction to AngularJS - Part 1

Client-Side Templates

Multi-page web applications create their HTML by assembling and joining it with data
on the server, and then shipping the finished pages up to the browser. Most single-page
applications—also known as AJAX apps—do this as well, to some extent. Angular is
different in that the template and data get shipped to the browser to be assembled there.
The role of the server then becomes only to serve as static resources for the templates
and to properly serve the data required by those templates.

Let’s see an example of what assembling this data and template on the browser looks
like in Angular. We’ll take the obligatory Hello, World example, but instead of writing
“Hello, World” as a single string, let’s structure the greeting “Hello” as data that we could
change later.

For it, we’ll create our template in hello.html:

<html ng-app>
<head>
 <script src="angular.js"></script>
 <script src="controllers.js"></script>
</head>
<body>
 <div ng-controller='HelloController'>
 <p>{{greeting.text}}, World</p>
 </div>
</body>
</html>

And our logic in controllers.js:


function HelloController($scope) {
 $scope.greeting = { text: 'Hello' };
}

Loading hello.html into any browser will then produce

Hello, World

There are a few interesting things to note here in comparison with most methods in
widespread use today:
• There are no classes or IDs in the HTML to identify where to attach event listeners.
• When HelloController set the greeting.text to Hello, we didn’t have to register
any event listeners or write any callbacks.
• HelloController is a plain JavaScript class, and doesn’t inherit from anything that
Angular provides.
• HelloController got the $scope object that it needed without having to create it.
• We didn’t have to call the HelloController’s constructor ourselves, or figure out
when to call it.

No comments:

Post a Comment