LxD Series: Starting AngularJS – Part 2

In previous post I wrote the very first AngularJS app which did nothing magical but showing the input text on page as I type.  Now I would like to get a grip on these weird attributes added in different HTML tags. For sake of reference I am writing program again.

 

<!doctype html>
<html ng-app>
<head>
    <title>Ng Addressbook</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js"></script>
</head>
<body>
<div>
    <input type="text" ng-model="Name" placeholder="Write your name">
    <h3>Hey {{Name}} how are you doing? Glad to know you executed your first Angular App successfully.</h3>
</div>
</body>
</html>

In AngularJS,these custom attributes are called directives which are understood and processed by AngularJS.

The first one we come across is ng-app. Ng prefix tells this attribute is actually Angular directive. This directive is actually setting name of your Angular application. When it’s set, AngularJS looks for this directive and convert the whole block into an Angular app. It is not necessary to add ng-app in <html> only. You could add it in any tag and make it Angular compatible. Thus, your html page could have both AngularJS and plain HTML code together.

Second directive which we come across is ng-model. If you are familiar with MVC architecture then you will be well aware about role of Model. ng-model provides data which is then processed by  Controller to show on page via View. Here model name is Name which is being used to bind data with input text. That is, when you write something in textbox it appears in <h3> tag just after it. This is not something new I know and many of us would have done it various time in jQuery or in Vanilla javascript. The beauty is that you did not need to add any EventListener here neither you had to use innerHTML or jQuery’s html() method. All done just by adding a custom attribute. IMO this is one of the strongest feature of Angular which Google engineer were successful to implement.

The last weird thing we saw in above code are {{ and }} which are being used as placeholder so that whatever is entered in input is stored in Name which then appears on page.

That’s it! In next couple of posts we will be working on listing page that will display data of contacts in tabular form. I am sure all of you would have done it many times. This time we will be doing it by using AngularJS. So stay tuned.

Like always, your feedback and comments are welcome.

 

Join with me and let’s learn together!

* indicates required