What is AngularJS
AngularJS is a front-end framework written in JavaScript and initially released in 2010. It is suitable for creating the so-called single-page application whereby you create parts for every application use case and some parts are displayed and some are not at any moment of time depending on the state of the application. AngularJS is based on declarative programming which implies describing what you would like to achieve rather than describing the algorithms of achieving the final go as in imperative programming.
For example, one can use conditionals and loops to implement an algorithm, but another option is to describe a set of desired results like in SQL, where one doesn’t need to know how the server works and executes queries. In the front end realm, imperative programming is represented by jQuery a part of which is used by AngularJS under the hood.
The main idea of AngularJS is it uses a thin server, which produces only data for an Angular application, but not HTML. AngularJS is used to create a fat client which consumes only data from a server and generates HTML on a client device on its own. The benefit of such approach is that HTML generation is crowdsourced, so it relieves the server from some burden. The downsides can include problems with Search Engine Optimization and longer loading times when an application is accessed for the first time.
Why AngularJS
In 2014 Google announced that AngularJS will be completely rewritten using TypeScript, a language developed by Microsoft and which can be transpiled to JavaScript. The new version of Angular was released in September 2016 is incompatible with the previous ones. Also, the JS suffix was dropped and the new product is called Angular. Although sometimes, AngularJS is referred to Angular 1 and Angular as Angular 2, it is recommended to refer to all versions as Angular.
It is important to know, that despite sharing the same name they are two different products, the former currently in version 1.6 and 1.7 is in the pipeline and the second is in version 2.3.0 and 4 is in the works. It should be noted, that in addition to TypeScript the development of Angular applications can be done in ECMAScript and Dart, a language developed by Google, but the majority of Angular tutorials are in TypeScript.
You may have a question why one should want to learn the older version and the answer is that there are a lot of legacy applications that need support, also, those legacy applications are often converted to newer versions of AngularJS and then converted to Angular. In addition, it is possible to develop AngularJS applications using TypeScript. So, good knowledge of AngularJS is a marketable skill.
Hello AngularJS World
Traditionally, programming tutorials start with printing a “Hello World!” message. Let’s do it for AngularJS. To get started one does not need to install something on the computer, it is possible to create a simple application using an online tool such as Plunker which itself is written in Angular or JSFiddle. We’ll discuss later how to create an AngularJS project later.
First, we need to create some HTML code that contains a single input field and a paragraph with the output text. The code is shown below.
After that, we should somehow inform Angular about the fact that this is an Angular app. These is accomplished using an ng-app attribute or directive in Angular lingo. In a nutshell, Angular adds some custom HTML tags and attributes and they are called directives.
The ng-app directive can be added to any tag, such as html, body, div or section. If you would like to manipulate the page title which is inside the head, you should definitely add the directive to the html tag. The body tag is also a common place to put the directive, but it could be placed on a div or section or some other tag. The actual tag we place the ng-app attribute can influence testing settings and we’ll talk about that later.
The idea of our application is to take data from the input field and add it to our greeting. To accomplish this task, we have to create some hidden variable that will store the input and put it into the output string. This is accomplished by the notion of the model which is used to store all the front end data. To create the variable one can use the ng-model attribute that contains the name of a variable as its parameter. The code is shown below.
Of course, we should add a reference to AngularJS file using HTML script tag. Oftentimes, the library’s code is taken from a Content Delivery Network, which spares your application from serving the code. Also, as will be shown later, one can download the code using Node Package Manager and serve it from one’s own machine. To render the content of the variable one uses double curly braces containing the name of the variable {{myModel}} and Angular replaces the construct with the content of the variable as can be seen in this Planker.
Adding a controller
Now, what if we would like to assign our variable a default value? This can be accomplished using JavaScript code. How do we attach the code to our page? The simple answer is that we proceed as usual with JavaScript, we add a <script> tag to our HTML code, where we place either our code or the reference to the *.js file containing the code. To elaborate more, Angular has a notion of a controller which is a piece of code that controls what and how is everything is displayed to the user.
Moreover, Angular adds the notion of a module to organize the code, so, first, we have to create a module, which we’ll do in a separate JavaScript file, then we’ll create the controller with a default value, and register the controller in the module and finally, we’ll add a reference to the code to HTML. The code of the controller is shown below.
We used the angular.module function with two arguments, a setter, to create a new module with the name app. The first argument is the name of the module, it should start with a lowercase letter, the second is the array of modules on which this particular one depends. The code for a big application can be split into several modules and the array is the place to put their names, but in our case, it is empty as we do not have any dependencies. The same function with a single argument, a getter, retrieves the module with the name specified.
Also, we add a controller and register it to the module. The name of the controller begins with an uppercase letter. The best practice is to use named functions to make the code more readable and easier to debug. In addition, it should be noted that we use a strange variable starting with a dollar sign called $scope. The first thing to mention about $scope is that it was used to store model data in early versions of AngularJS, but currently this is not the recommended way to go; I mentioned it here because you can find it in legacy codebases and some tutorials. Later I’ll show you the recommended way to store model variables.
The second thing is that we do not pass the $scope variable to our function and in a plain-vanilla JavaScript it would be an error as the variable $scope will be undefined. But we are going to use this function inside an AngularJS application and Angular will provide the method with an instance of a scope variable. This is called Dependency Injection which simply means that by providing the argument list to your controller you ask Angular create variables if not exist and pass them as parameters. This could be easily done with Angular built-in variables and is also possible with your custom variables and methods, but you have to provide Angular with recipes how to create them.
Now, in the code of controller we add myModel variable to the scope and after that, we should inform our application how to get our code. We add a <script> tag, after that supply the name of the module to our ng-app attribute as a parameter and add the ng-controller attribute with the name of the controller to the section tag. The modified HTML code is shown below.
Priming the code for minification
Now let’s think how we can improve our JavaScript code from the point of view of performance. On the one hand, we should use meaningful names for our variables and functions to make our code readable. On the other hand, each letter in a name adds to the amount of data served by our server, and if we take for example Facebook which has more than a billion of users, each letter translates to more than billion letters transmitted to all users. The common solution to the problem is to minify the code, that is we use long names in the code, but a special program replaces long names with single variables before we put our code into the production environment.
All this well and good, but the dependency injection system will not understand what to inject because the names of functions’ arguments change after minification. The first approach to not breaking dependency injection is to provide the initial names of the variables inside an array which contains the controller function as well. The code is shown below.
You can find such code in some applications, but it is often criticized for poor readability as the list of dependencies can be long and strings and a function are mixed in the array. Another approach is to use $inject which is displayed below along with the code of the controller.
The complete Plunker application is here.
Removing variables from the global scope
It is a best practice to separate code into several files, but using named functions may lead to name collisions when the code is minified and merged into a single file. To prevent this one can use an Immediately Invoked Function Expression (IIFE). Long story short, to create an IIFE one should type two pairs of parenthesis followed by a semicolon ()();, place an anonymous function inside the first (function(){})(); and then the code to be removed from the global scope is to be placed inside the curly braces. The code snippet below shows how to use the idiom.
Several AngularJS applications on the same page
You may have a question whether only a single application can be placed on a page and the answer is that you can place several, but the ng-app directive won’t help you. Actually, if you try, the second application won’t work. The solution is to bootstrap your second application on your own using angular.bootstrap() method. The code for this is shown here; you can comment out the bootstrap code and see what happens. The downside of this approach is that you can face some hurdles when using tools for testing your application.
Summary
In this tutorial, we’ve built a Hello World AngularJS application. In the next installment of this series, you’ll learn how to work with Angular on your local machine using a free multi-platform editor Visual Studio Code and how to add static analysis to your application to improve code quality.
Resources
AngularJS is a front-end framework written in JavaScript and initially released in 2010. It is suitable for creating the so-called single-page application whereby you create parts for every application use case and some parts are displayed and some are not at any moment of time depending on the state of the application. AngularJS is based on declarative programming which implies describing what you would like to achieve rather than describing the algorithms of achieving the final go as in imperative programming.
For example, one can use conditionals and loops to implement an algorithm, but another option is to describe a set of desired results like in SQL, where one doesn’t need to know how the server works and executes queries. In the front end realm, imperative programming is represented by jQuery a part of which is used by AngularJS under the hood.
The main idea of AngularJS is it uses a thin server, which produces only data for an Angular application, but not HTML. AngularJS is used to create a fat client which consumes only data from a server and generates HTML on a client device on its own. The benefit of such approach is that HTML generation is crowdsourced, so it relieves the server from some burden. The downsides can include problems with Search Engine Optimization and longer loading times when an application is accessed for the first time.
In 2014 Google announced that AngularJS will be completely rewritten using TypeScript, a language developed by Microsoft and which can be transpiled to JavaScript. The new version of Angular was released in September 2016 is incompatible with the previous ones. Also, the JS suffix was dropped and the new product is called Angular. Although sometimes, AngularJS is referred to Angular 1 and Angular as Angular 2, it is recommended to refer to all versions as Angular.
It is important to know, that despite sharing the same name they are two different products, the former currently in version 1.6 and 1.7 is in the pipeline and the second is in version 2.3.0 and 4 is in the works. It should be noted, that in addition to TypeScript the development of Angular applications can be done in ECMAScript and Dart, a language developed by Google, but the majority of Angular tutorials are in TypeScript.
You may have a question why one should want to learn the older version and the answer is that there are a lot of legacy applications that need support, also, those legacy applications are often converted to newer versions of AngularJS and then converted to Angular. In addition, it is possible to develop AngularJS applications using TypeScript. So, good knowledge of AngularJS is a marketable skill.
Traditionally, programming tutorials start with printing a “Hello World!” message. Let’s do it for AngularJS. To get started one does not need to install something on the computer, it is possible to create a simple application using an online tool such as Plunker which itself is written in Angular or JSFiddle. We’ll discuss later how to create an AngularJS project later.
First, we need to create some HTML code that contains a single input field and a paragraph with the output text. The code is shown below.
After that, we should somehow inform Angular about the fact that this is an Angular app. These is accomplished using an ng-app attribute or directive in Angular lingo. In a nutshell, Angular adds some custom HTML tags and attributes and they are called directives.
The ng-app directive can be added to any tag, such as html, body, div or section. If you would like to manipulate the page title which is inside the head, you should definitely add the directive to the html tag. The body tag is also a common place to put the directive, but it could be placed on a div or section or some other tag. The actual tag we place the ng-app attribute can influence testing settings and we’ll talk about that later.
The idea of our application is to take data from the input field and add it to our greeting. To accomplish this task, we have to create some hidden variable that will store the input and put it into the output string. This is accomplished by the notion of the model which is used to store all the front end data. To create the variable one can use the ng-model attribute that contains the name of a variable as its parameter. The code is shown below.
Of course, we should add a reference to AngularJS file using HTML script tag. Oftentimes, the library’s code is taken from a Content Delivery Network, which spares your application from serving the code. Also, as will be shown later, one can download the code using Node Package Manager and serve it from one’s own machine. To render the content of the variable one uses double curly braces containing the name of the variable {{myModel}} and Angular replaces the construct with the content of the variable as can be seen in this Planker.
Now, what if we would like to assign our variable a default value? This can be accomplished using JavaScript code. How do we attach the code to our page? The simple answer is that we proceed as usual with JavaScript, we add a <script> tag to our HTML code, where we place either our code or the reference to the *.js file containing the code. To elaborate more, Angular has a notion of a controller which is a piece of code that controls what and how is everything is displayed to the user.
Moreover, Angular adds the notion of a module to organize the code, so, first, we have to create a module, which we’ll do in a separate JavaScript file, then we’ll create the controller with a default value, and register the controller in the module and finally, we’ll add a reference to the code to HTML. The code of the controller is shown below.
We used the angular.module function with two arguments, a setter, to create a new module with the name app. The first argument is the name of the module, it should start with a lowercase letter, the second is the array of modules on which this particular one depends. The code for a big application can be split into several modules and the array is the place to put their names, but in our case, it is empty as we do not have any dependencies. The same function with a single argument, a getter, retrieves the module with the name specified.
Also, we add a controller and register it to the module. The name of the controller begins with an uppercase letter. The best practice is to use named functions to make the code more readable and easier to debug. In addition, it should be noted that we use a strange variable starting with a dollar sign called $scope. The first thing to mention about $scope is that it was used to store model data in early versions of AngularJS, but currently this is not the recommended way to go; I mentioned it here because you can find it in legacy codebases and some tutorials. Later I’ll show you the recommended way to store model variables.
The second thing is that we do not pass the $scope variable to our function and in a plain-vanilla JavaScript it would be an error as the variable $scope will be undefined. But we are going to use this function inside an AngularJS application and Angular will provide the method with an instance of a scope variable. This is called Dependency Injection which simply means that by providing the argument list to your controller you ask Angular create variables if not exist and pass them as parameters. This could be easily done with Angular built-in variables and is also possible with your custom variables and methods, but you have to provide Angular with recipes how to create them.
Now, in the code of controller we add myModel variable to the scope and after that, we should inform our application how to get our code. We add a <script> tag, after that supply the name of the module to our ng-app attribute as a parameter and add the ng-controller attribute with the name of the controller to the section tag. The modified HTML code is shown below.
Now let’s think how we can improve our JavaScript code from the point of view of performance. On the one hand, we should use meaningful names for our variables and functions to make our code readable. On the other hand, each letter in a name adds to the amount of data served by our server, and if we take for example Facebook which has more than a billion of users, each letter translates to more than billion letters transmitted to all users. The common solution to the problem is to minify the code, that is we use long names in the code, but a special program replaces long names with single variables before we put our code into the production environment.
All this well and good, but the dependency injection system will not understand what to inject because the names of functions’ arguments change after minification. The first approach to not breaking dependency injection is to provide the initial names of the variables inside an array which contains the controller function as well. The code is shown below.
You can find such code in some applications, but it is often criticized for poor readability as the list of dependencies can be long and strings and a function are mixed in the array. Another approach is to use $inject which is displayed below along with the code of the controller.
The complete Plunker application is here.
It is a best practice to separate code into several files, but using named functions may lead to name collisions when the code is minified and merged into a single file. To prevent this one can use an Immediately Invoked Function Expression (IIFE). Long story short, to create an IIFE one should type two pairs of parenthesis followed by a semicolon ()();, place an anonymous function inside the first (function(){})(); and then the code to be removed from the global scope is to be placed inside the curly braces. The code snippet below shows how to use the idiom.
You may have a question whether only a single application can be placed on a page and the answer is that you can place several, but the ng-app directive won’t help you. Actually, if you try, the second application won’t work. The solution is to bootstrap your second application on your own using angular.bootstrap() method. The code for this is shown here; you can comment out the bootstrap code and see what happens. The downside of this approach is that you can face some hurdles when using tools for testing your application.
In this tutorial, we’ve built a Hello World AngularJS application. In the next installment of this series, you’ll learn how to work with Angular on your local machine using a free multi-platform editor Visual Studio Code and how to add static analysis to your application to improve code quality.
Resources