First solid steps into AngularJS - DEFEATING THE DRAGON - JavaScript in Plain Language (2015)

JavaScript in Plain Language (2015)

PART V: DEFEATING THE DRAGON

Welcome to modern DOM scripting.

October 2015

5.1 First solid steps into AngularJS

Intro

AngularJS is a framework for developing dynamic web pages. It was created by Google to address multiple problems with conventional web design. As many other developers, I believe AngularJS is the hottest technology available and the future of web design, and because it is backed by Google, there will be plenty of resources to make it stick.

In a way, AngularJS extends HTML attributes, giving them superpowers thanks to the library provided by AngularJS. The library is connected to your webpage via a link just like you would do for CSS or JavaScript.

HTML was designed for static pages. AngularJS is what HTML could have been if it was designed for modern applications.

At this point you really need to know basic HTML because we will be working with a standard HTML page. You don’t need to be an expert, the very basic stuff will do. If you need to refresh your mind or learn from scratch, give Codecademy a visit. You may see me there at times as a moderator, especially on their JavaScript exercises, but their HTML tutorial is pretty cool and free!!

Links of interest (for future reference):

AngularJS.org | Wikipedia | Documentation.

Before you get yourself lost reading their material let’s become familiar with the basic setup and what it can do for a web developer trying to design a more dynamic web page.

Welcome to modern web design!

Directives

How does AngularJS extend HTML capabilities?

First we provide a link on the web page to the AngularJS’ library, just like we would link to a JavaScript or a CSS file.

Then the page becomes linked to this huge plethora of methods that can be used by you.

Let’s suppose that we want to supercharge a DIV and nothing else on the page, like for example, you want to create a box in your web page with some dynamic data.

After linking to the library, all we have to do is to apply a directive to the DIV. The directive is ng-app, which makes this DIV an application controlled by AngularJS. The ng-app directive tells AngularJS that this DIV needs to be scanned for possible AngularJS functionality. We will see how this works in a moment.

If we want the whole page to be scanned and mapped, we apply the same directive to the HTML tag instead of applying it to a DIV. Actually, any HTML tag able to be a container can become an Angular supercharged element without even affecting the rest of the page. We could use a paragraph tag, or a form tag, or an ordered list. For the most part however, AngularJS is so friendly that we don’t mind associating the whole page to it.

Please look at the following image to have a better idea of what I mean:

Fig 23 see raw file | html

The above image is a basic HTML page with nothing in the BODY but the word hello.

Well, that is not true. At the bottom of the BODY (as the last thing to be written in the body) we also have a link to the AngularJS library which should be (as of October 2015):

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

You can also substitute the http for an https.

In the future, to get the latest link version, go to angularJS.org and click on Download. A window will pop up with different ways of accessing the library. Copy the link on the CDN window and paste it in your web page inside of the opening script tag as shown above. For our exercises you don’t have to do this step, just copy the raw file (see link below the image) as your starting HTML skeleton page.

The reason to include the link to the library at the very bottom of the BODY container is to make sure that all the HTML elements load into the browser before calling the library. As an alternative we could include the link in the HEAD section like we normally do for CSS, but then we would have to make sure that there were no side effects by calling the library prematurely.

On line 6 I have included a directive ng-app. That will tell AngularJS that everything within the <html> and </html> tags can use the tools available at Google’s AngularJS library. In other words, the whole HTML page has been extended with more functionality. The trick is to know what functionality is available and what we can do with it.

There is a lot to learn about it and I will provide links for further studies after we conquer the biggest barrier: The first step toward AngularJS’ world.

What is a library?

A library is a collection of functions which are useful when writing web applications. They can be called when needed.

What is a framework?

A framework is a particular implementation of a web application. In a framework your code fills in the details. The framework is in charge and it calls into your code when it needs something “app” specific.

What is a directive?

A directive is something that introduces new functionality to the existing standard syntax. It expands the syntax's capability, it’s a way of teaching an old dog new tricks. By attaching a directive to an existing HTML tag, the behavior of that tag changes by what is written on the Angular's library under the name of such directive. In some cases directives specify global behavior, while in other cases they only affect a local section, such as a block of programming code.

AngularJS teaches the browser new syntax through constructs called directives.

If you ever built web applications before, Angular will be a total new paradigm. If you are new to web design, AngularJS will teach you modern and best practices and consider yourself lucky because you don’t have to forget the old in order to learn the new.

Yes there is a price to pay at first, you lose flexibility. What you gain in return is consistency, speed of development, and something that works today and tomorrow. You no longer need to know how to build a motor in order to drive the car, but the more you know the better you will take advantage of what the car has to offer. AngularJS is not an easy technology to learn, but if you have made it up to here in this book, then you have gotten the discipline and skill to learn and master AngularJS.

What does ng-app mean?

It just tells the browser to use AngularJS as the root of the page, or as the root of the DIV, depending where we insert the ng-app tag. In this way everything will be relative to AngularJS which provides core functionality to your page.

In this example,

<html ng-app>

The whole page uses AngularJS as its root.

In this example,

<div ng-app>

Only this DIV uses AngularJS as its root. The rest of the web is not aware of AngularJS.

We can also name the application we are building by adding the app name to the directive:

<html ng-app="myApp">

This becomes very useful as you will see soon.

Because the application name inclusion on the ng-app directive is very common, you will see the following syntax in many articles out there:

<html ng-app="">

That’s another way of writing a directive with no name, instead of just writing ng-app by itself

· Note: Do not include a name unless such name exists as a Module because AngularJS will not work. We haven’t covered Modules yet so, for now, we only use ng-app by itself, and it is perfectly fine to do so even in production.

· Note: Notice how ng-app="" does not have a blank space between quotes. A blank space would be considered a name (even if blank) and a Module under that name would have to be created. Again, let’s just use ng-app by itself for now.

No more DOM manipulation tasks

The Document Object Module or DOM is the map layout of all existing HTML tags or nodes. In order to write a result of a JavaScript program in a web page we need to address the DOM location where we want to implement the scripted result. This has always been a problem due to browser inconstancies and implementation errors. Then jQuery was invented. jQuery is a library of methods used to address the DOM. When properly implemented, jQuery works great. Unfortunately the usage of jQuery has become a problem because many users do not learn JavaScript, they just memorize jQuery solutions and jQuery is manually driven leading to implementation errors.

AngularJS has come to the rescue. The low level implementation will no longer be done by the programmer him/herself; it will be done by AngularJS based of the programmer’s expressive desires for a certain outcome. The programmer has become a plumber; it plugs in the correct directive for the desired outcome. This will assure best practices and error free implementations. With AngularJS you are freed from low level manipulation tasks and you can use your extra time to think of solutions instead of code grammar and security implementations.

Of course, if you know jQuery you can still use it with AngularJS, but I suspect that AngularJS will develop more and more ways to avoid some of the jQuery popular implementations.

In AngularJS, the only place where an application touches the DOM is within directives. If however you need to access the DOM directly you can still do it through the writing of custom directives | bit.ly/1tYW95Q

Ok, we now know a bit about directives. Let’s review the meaning of expressions so that we can expand our AngularJS topic.

What is an expression?

Do you remember from a previous chapter what expressions were?

An expression is something JavaScript evaluates to a single value.

2 + 5;
// evaluates to 7

"tony"
// evaluates to tony

"hello".toUpperCase();
// evaluates to "HELLO"

and so on...

If, on our web page we have an expression that needs to be passed into AngularJS in order to be evaluated by the JavaScript interpreter, we do so by wrapping it in double braces:

{{ this expression }}

AngularJS will write the result of a JavaScript evaluation exactly where the braces are located on the web page. This is not an AngularJS invention; it has been implemented by other libraries away before AngularJS. Just take a quick look at Mustache | bit.ly/1DxihbF.

Let’s play with a couple of examples. It will not be anything practical but it serves to familiarize us with passing expressions to AngularJS.

Note: You still can use jsbeautifier.org as an editor but unfortunately you cannot save your files unless you paste your code onto another plain text editor. NOTEPAD comes to mind. If you’ve done HTML before you probably already have a favorite editor that you can use.

1- First we fetch our sample HTML script:
raw file

2- Paste it onto a local editor like for example Windows NOTEPAD ( I also use the free and colorful Programmer’s Notepad from pnotepad.org). Save it as an HTML file. I will call my file ang2.htm. Make sure you create a new folder just for our examples.

3- To test it, go to your file list and double click on the file. Since it is an HTML file it will open in the browser and you should see the word hello.

4- Now that we know the file works, let’s go back to the editor and add an expression. Replace the word hello with the following sentence and expression:

Convert the expression tony to uppercase: {{"tony".toUpperCase();}}

5- Save the file, refresh your browser or reopen the file, and you should see the word TONY in upper case.

See the image below for an explanation:

Fig 24 see raw file | html

The HTML script is still the same as before. We only replaced the word hello with the sentence seen on line 11, followed by {{"tony".toUpperCase();}}.

Anything written inside of the double curly braces is to be evaluated by JavaScript.

Do you see yourself adding JavaScript evaluation results to your existent HTML pages?

Even if you don’t make the whole page an AngularJS app, you could still reserve one paragraph or one DIV for some output you may need to ask AngularJS to process.

On the next image we have the same script but this time I only reserved one little space inside of a DIV for AngularJS processing, instead of declaring the whole web page as an AngularJS app:

Fig 25 see raw file | html

From line 8 through 12 I declared a DIV and assigned it to AngularJS by including the directive ng-app.

On line 10, I wrote a message in plain text, and then I included 10 + 9 inside of the double braces. This will instruct AngularJS to have this expression evaluated by JavaScript.

I didn’t write any JavaScript code. AngularJS took care of the internal process. This is programming at a higher level of abstraction. Do we still need to know JavaScript? Of course we do! Your knowledge of JavaScript will become necessary when we go beyond this simple testing.

Do I always have to include my expressions on my web page?

No, we are doing it just for testing and understanding purposes before introducing the module and controller. But yes, you can always do this in production and it should work for simple stuff.

ng-init

Let’s introduce another directive so that we have more tools to play with.

· An ng-app directive initializes the AngularJS application.

· An ng-init directive initializes some data to be used on the application.

Let’s see how ng-init works in its simplest form:

1- Open your basic HTML script and modify the HTML tag to contain a second directive as follows:

<html ng-app ng-init="city='Harrisburg'; state='Pennsylvania'">

2- Then in the body write the following:

Do you know {{city}} is the capital of {{state}}?

3- Save it as ang5.html and test it.

You should see the following sentence on your browser display:
Do you know Harrisburg is the capital of Pennsylvania?

Fig 26 raw file | html

Do you see what happened?

We initialized two variables by using ng-init: city and state, and then we were able to process them via two expression tags on the HTML output. There was no need to address the DOM with complicated scripting. There are better ways to do this but right now the purpose is to become familiar with the AngularJS’ basic tools.

By initializing the arguments city and state on the HTML tag they became available to use on the web page. However these variables are normally placed on a separate sheet.

ng-bind

Just to illustrate the purpose of the double curly braces, let’s write the same script in a different way: by using a directive called ng-bind.

6- I’m only doing it for variable city and not for variable state just to show how both will work:

Do you know <span ng-bind="city"></span> is the capital of {{state}}?

And the display will be:

Do you know Harrisburg is the capital of Pennsylvania?

Actually, AngularJS always replaces the curly braces with ng-bind in its internal process. If you don’t mind writing the extra SPAN tag this actually works a bit faster. When you refresh the page (CTRL f5 on Windows) and focus on the output, you will see that Harrisburg shows up immediately, whereas Pennsylvania will first show the braces and then it converts to the proper word. It happens very fast but you might be able to catch it.

What does ng-bind do?

It binds data source to target. No need to play the getElementById DOM game anymore.

There is a lot more to know about AngularJS binding but we need to go slow and just grasp enough to understand what comes next. It is like that famous expression “Rome wasn’t built in a day”.

ng-cloak: Avoiding display flickering

When using the curly braces {{ }} instead of <span ng-bind="city"> you may notice a quick flicker on the display because the curly braces have not yet been evaluated by AngularJS.

If that becomes a problem for you, include the link to the library in the HEAD section instead of the BODY section. This way, the curly braces will be evaluated before the browser displays the document. Including the link in the head may have some side effects, depending on the complexity of your page, hence the reason why more and more developers are moving library links to the bottom of the page.

If you are embedding AngularJS on a page but you have no access to the HEAD script, then you may use ng-bind instead of the curly braces, or you could use ng-cloak.

Since ng-cloak involves CSS, I am not going to describe here. Please check the following link for a full description of this implementation:
docs.angularjs.org/api/ng/directive/ngCloak. | bit.ly/1pcTqjF