Beginner’s Guide To AngularJS

Beginner’s Guide To AngularJS

Welcome to a Beginner’s Guide To AngularJs.  AngularJS, commonly referred to as simply Angular, is a structural framework, developed by Google, to create highly dynamic web applications. Angular hooks directly into HTML’s syntax to allow your application’s components, making it extremely easy to add Angular to an existing website or template. Using data binding and dependency injection, Angular is able to drastically eliminate the amount of code you need to write and maintain. On top of that, Angular comes with the ability to perform both Unit Tests, and End-To-End Tests to help ensure every aspect of your application is running as intended.

What Is AngularJS

This blog post will cover the basics of getting an Angular application up and running, along with several other current “best practices”.

This blog post is written with respect to the Angular 1.3.x branch:

https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js

Table of Contents


Your First Creation

First things first. Before we can build anything using Angular, we’ll need to create a new HTML file and import AngularJS. To do this, we’re going to utilize Google’s CDN.

%MINIFYHTMLbab1a639d4850111612708c25f9bf3758%

Now that we have laid the foundation by including the Angular javascript file we can start making our application

Extending the HTML

Earlier, I mentioned AngularJS hooks into a web page simply by extending the HTML. It does this by utilizing directives. At a high level, directives are markers on a DOM element that tells Angular’s HTML compiler to attach a specified behavior to that DOM element. Angular comes with a number of built-in directives, like ngBind, ngModel, and ngClass. In addition, if Angular doesn’t already contain a directive to do what you want, you can easily create your own to accomplish your goals.
One thing you’ll notice is all of these directives began with two letters, ng. Angular uses this with their built-in directives to help users differentiate between the built-in directives and user created ones.

For our first application we’ll be using three directives:

  1. ngApp – This defines the namespace in which your application will interact. It is possible to have multiple ngApp declarations on a single page all executing within their own scope.
  2. ngModel – This directive binds data from HTML controls, such as input fields, checkboxes, and text areas into the application’s scope.
  3. ngBind – The last directive we’ll be using continuously updates the text inside an element with data from your application.

Next, we will need to do is declare where on our page the application will reside. You can attach this to any HTML element on the page, such as a

element, the element, or even the element. For our example, we’re going to attach it to a newly created

element inside the as follows:

You will have noticed the attribute we added to the div element wasn’t ngApp, but instead data-ng-app. Angular follows a design pattern where directives are all camelCase meaning the first word is all lower case, there are no spaces, and every word thereafter starts with a capital letter), while the associated HTML convention is all lower case with words separated by hyphens. The reason we added data- in front and hyphenated ng-app is because we want to keep our document HTML5 valid. You can remove the data- and simply have ng-app=””, and your angular will work just fine.

Now that we have declared the space our application will control, let’s have it do something!

Within our newly created application division, let’s insert the following code:

This snippet of code has two components. First, we added an input field and assigned it the attribute data-ng-model=”FirstName”. This tells Angular that whatever a user types into this input field need to be bound to the variable FirstName within the application’s scope. We’ll go into the application scope later on.

The second thing we added was the data-ng-bind=”FirstName” attribute onto a paragraph, element. This attribute tells Angular that we want the contents of this paragraph element to display whatever data is currently bound to the FirstName variable inside the application’s scope.

Putting it all Together

Your current HTML document should look something like this:

%MINIFYHTMLbab1a639d4850111612708c25f9bf3759%

Open this file in your browser of choice and simply type your first name into the input field. You’ll notice the web page updates in real time with whatever you type.

(Internet Explorer Users: You might receive a notification that Internet Explorer restricted this web page from running scripts or ActiveX controls. If so, all you need to do is click the ‘Allow blocked content’ button to enable javascript).

Congratulations, you’ve made your first Angular application!


Expressions

As we saw in the last example when using the ngBind directive we need to attach it directly to an HTML element. By doing so, Angular constantly replaces that elements contents with the bound variable’s value. What if, instead of simply displaying your first name, we wanted to preface it with “Hello, ” greeting? We would need to modify our code to be:

Hello

While this will work, you can imagine that once you have a lot of different dynamic elements your code will become extremely cluttered. As an alternative Angular provides Expressions. Expressions work similar to ngBind by allowing the developer to place javascript code directly onto the page.

Below, is an example of using Expressions instead of ngBind to display our dynamic data.

Hello {{FirstName}}

Notice that in Angular, Expressions are denoted by wrapping your javascript code in double curly-braces. Also, the HTML quotation marks are no longer needed since FirstName is now a true variable. It’s as simple as that.

Notice in my previous statement I said Expressions are able to wrap javascript code. We can also place logical components, like mathematical expressions.

{{2+3}}

In addition to simple inline statements, we can also execute functions inside of an Expression. While we aren’t quite ready to create functions, they will come along shortly.


Controllers

Up to this point, we really haven’t done much coding and our application is fairly simple. This is about to change. We’re going to look into creating our own ngController to help us add some complexity and functionality to our application.

The first thing we’re going to do is create our modules. You’ll remember from the first page I hinted about how Angular supports a very compartmentalized structure allowing for a high degree of code re-usability and maintainability. Angular does this by using what it calls Modules.

Declaring our Application

To get started we need to declare our application inside of our HTML. You do this by adding the name of your application inside the ng-app=”” section. For this example, let’s call our application myApp; so our resulting HTML would look like this:

Now that we have declared our application, we need to actually create it within our javascript. When you start building real applications, you will want to create individual javascript files for each module. However, for the sake of this example we are going to keep everything inside a single document.

To create our myApp application inside Angular, we need to add the following block of javascript code:

var app = angular.module("myApp", []);

Seems easy enough, right? Well, there are several important things going on here, despite the small amount of code we added.
First, you will notice we are declaring a variable, app, to be our binding point for the application module. This comes in handy later on when creating things like controllers, services, or even our own directives.
Second, you will notice the angular.module() function takes two parameters: the name of the module, in this case, “myApp”, and an array which is used for injecting services into our application. For now, we will leave it empty and we won’t worry about it.

Registering a Controller

Now that we have declared our application and bound it to a variable, the next step is to actually create a controller module. To do so, we use our app variable as such:

var app = angular.module("myApp", []);
app.controller("myController", function($scope) {

});

If you are not familiar with typical object notation, this might look a little weird. What we just did is tell Angular that we wanted to attach a controller to our myApp module. To create a controller, we need to pass two parameters. The first parameter is the controller’s name; in our case “myController“. We are also passing a second parameter, and that is a function of a parameter called $scope. Remember earlier when I mentioned an application’s scope? Well, this is it! When we create a controller for an application Angular is passing that applications $scope variable into the controller for us to manipulate. It’s also important to remember that earlier I said ngModel was binding FirstName to our scope. When the application initialized, Angular created a variable on the $scope object named FirstName that stores that information.

Now that we’ve registered our controller, we need to place it inside the HTML so that angular knows what region it has control over. Similarly to how we declared our application, we need to attach the ngController directive to an element inside our page.

When all is said and done, our resulting HTML document should look like this:

%MINIFYHTMLbab1a639d4850111612708c25f9bf37510%%MINIFYHTMLbab1a639d4850111612708c25f9bf37511%
Hello, {{FirstName}}

Now that we have laid the application/controller foundation we can really start making our application dynamic!


Manipulating the $scope

Once we have successfully declared our application and attached a controller to be used we can begin adding properties to the $scope to be used inside the HTML.

Dot Notation

Let’s start by adding a variable to the $scope object. We can accomplish this by modifying the contents of our controller function.

If you recall, objects in javascript can have properties added to them at any point using the dot notation. For example, let’s say we want a Person object in javascript. To create this object, all we need to do is the following:

var Person = {};

This will initialize the variable Person to be an empty object. Now, lets add the properties FirstName and LastName to the person object. We can do that in two different ways. The first would define those properties when we initialize the Person object:

var Person = {
    FirstName: "",
    LastName: ""
};

Alternatively, we can use the dot notation to add those properties to an already created Person object:

var Person = {};
Person.FirstName = "";
Person.LastName = "";

Angular utilizes this second (dot notation) method to dynamically create variables as needed. That’s how our early code worked — there was an implicit $scope variable that dynamically gained the property FirstName when we attached it to the input field using the ngModel directive.

Adding Our First Variable

Using what we just learned about how Angular utilizes Dot Notation to dynamically create properties on the $scope variable, let’s add a property called FirstName to the $scope:

app.controller("myController", function($scope) {
    $scope.FirstName = "Brandon";
});

Place the updated controller inside your HTML page and see what happens.

If you’re curious how this might be applicable, place the following code in a new HTML document and open it in your browser:

%MINIFYHTMLbab1a639d4850111612708c25f9bf37512%%MINIFYHTMLbab1a639d4850111612708c25f9bf37513%
{{WidgetCount}} widgets would cost you ${{WidgetCount * WidgetPrice}}

Pretty cool, eh!

Creating a Function

Variables are nice and all, but the real programming power comes from functions. Functions are attached to the $scope in a very similar manner to variables. Start off by updating our HTML document to ask for the visitor’s First and Last name.

Hello, {{FirstName}} {{LastName}}

Now that we have that in place, instead of displaying the visitor’s name using two expressions, lets create a function that does it for us.

Inside of our Controller module, attach a function named CombineName to our $scope variable

app.controller("myController", function($scope) {
	$scope.CombineName = function(){
	
	};
});

We just told Angular that whenever the CombineName $scope variable is called, it needs to execute this function. Define this function to return a string of FirstName LastName:

app.controller("myController", function($scope) {
	$scope.FirstName = "";
	$scope.LastName = "";
	$scope.CombineName = function(){
		return $scope.FirstName + " " + $scope.LastName;
	};
});

Finally, now that our function is set up and ready to rock, lets update our HTML page to call this function:

Hello, {{CombineName()}}

Our resulting HTML document should look like this:

%MINIFYHTMLbab1a639d4850111612708c25f9bf37514%%MINIFYHTMLbab1a639d4850111612708c25f9bf37515%

Hello, {{CombineName()}}


Directives, Directives, Directives

While Angular comes with a large number of built-in Directives, for this course I’m only going to cover a few of the most commonly used ones. To see a full list of directives, visit Angular’s Directive API page.

ngShow (https://docs.angularjs.org/api/ng/directive/ngShow)

In our previous examples, the document looks a little funny saying “Hello, ” before a visitor enters their name. The ngShow directive will allow us to dynamically control when elements are displayed depending if its value is true (show the element) or false (hide the element). Now having ng-show=”true” or ng-show=”false” isn’t that dynamic, or even that useful. Instead, when using the ngShow directive we can give it an expression to evaluate.

Let’s update our HTML page to hide the “Hello,” text if the contents of FirstName is empty.

Hello, {{CombineName()}}

By adding this directive onto the page, we are directing the browser to show the text “Hello” only when the $scope variable FirstName is not empty (i.e. has a length greater than 0). Now, as soon as the visitor starts typing their first name you’ll notice the paragraph element switches from hidden to shown.

ngInit (https://docs.angularjs.org/api/ng/directive/ngInit)
The ngInit directive allows us to execute an expression the first time that element is initialized. Typically, this directive is placed on the same element as the ngController to call some function. Let’s say you were creating an application that displayed information about employees at a company such as their name, hire date, department, etc… To get this information, we need to pass Angular the Employee’s ID in order to an out database and extract the information. While we won’t be doing the data gathering methods (that will come later) we will stub it in for this example.

%MINIFYHTMLbab1a639d4850111612708c25f9bf37516%%MINIFYHTMLbab1a639d4850111612708c25f9bf37517%
{{FirstName}}
{{LastName}}
{{Department}}

This example we had ngInit call a function attached to the $scope named GetEmployeeData() and pass the parameter employeeID to be used inside that function. Pretty easy, right?

ngClick (https://docs.angularjs.org/api/ng/directive/ngClick)

The ngClick directive is very similar to javascript’s onClick method. When attached to an HTML element and, that element is clicked the directive will execute whatever expression it currently holds. Let’s modify our HTML document to include a button that, when clicked will say “Hello” to the visitor.

First, we need to add an element to the page that we want users to click. For this, let’s use a simple button.

The next thing we need to do is attach the ngClick directive to our button. For now, let’s assume when clicked we’re going to call a function on the $scope called Greeting().

Next, let’s create the $scope function to execute when that button is clicked.

$scope.Greeting = function(){
    alert("Hello " + $scope.FirstName + " " + $scope.LastName);
};

ngRepeat (https://docs.angularjs.org/api/ng/directive/ngRepeat)

The final directive I’m going to touch on is the ngRepeat directive. Angular’s ngRepeat directive allows us to display repeatable data, such as a list, without knowing anything more than the property of each list item. Let’s take this course for example. We have a number of students registered for this course, each of which has a First Name and the Last Name. If we want to display this list of information to a visitor, we could use the ngRepeat directive to cycle through a list of students and output each of their names.

To start, we will need a class list (or array) of students:

var Person1 = {
    "FirstName": "John",
    "LastName": "Doe"
};
var Person2 = {
    "FirstName": "Jane",
    "LastName": "Row",
};
var Person3 = {
    "FirstName": "Joe",
    "LastName": "Smith"
};
$scope.People = [
    Person1,
    Person2,
    Person3
];

Place that javascript code into your controller.

Next, we need to display that information on our page. Let’s use a table to display that information:

First NameLast Name
{{item.FirstName}}{{item.LastName}}

There are a few interesting components to the ngRepeat directive worth discussing in more detail.

First, notice the expression we are using here. The ngRepeat directive works similarly to a for each loop. In this code, we are saying “For each item inside of the People $scope variable, execute the following code”. What follows is whatever HTML we need, including the element containing the ngRepeat attribute.

	{{item.FirstName}}
	{{item.LastName}}

Second, notice how the expression was “item in People“. To Angular, we’re defining the variable item as the temporary holder for the current object. On the first pass through, item will be {“FirstName”: “John”,”LastName”: “Doe”}, and on the second pass through item will be {“FirstName”: “Jane”,”LastName”: “Row”}, and on the third and final pass through item will be {“FirstName”: “Joe”,”LastName”: “Smith”}. This explains why we had to have {{item.FirstName}} instead of {{FirstName}} in each expression.


The $http Service

While we have made a fairly decent Angular application thus far, everybody knows that real applications need to be able to send and receive data with different web services (like APIs). This allows your application to truly be dynamic. To accomplish that, we’ll utilize one of Angular’s built-in services, the $http service.

Services

Before we dive into the $http service we should first talk about Services in general. Similarly to directives, Angular comes with a number of built-in services we can use right out of the box. Just like directives, if Angular doesn’t already have a service that accomplishes what you are looking to do, you can always make your own. Angular Services are basically substitutable objects that can be injected into controllers. This follows Angular’s pattern of trying to keep things modular. If multiple controllers are going to need access to the same object, containing the same information and functions, you need to create a Service and inject that service into your controllers. The really neat thing about Services is they can hold information outside of the controller scope. This means you can have multiple controllers on a single page talking to each other by passing data through a Service.

The $digest Cycle

If you’ve previously used AJAX (Asynchronous JavaScript + XML) you might be curious why we can’t just use that and instead need to use Angular’s $http service. Angular has a unique way of watching the DOM as well as it’s internal application scope. If you change a variable, either on the DOM or inside the application’s $scope using javascript outside of Angular it won’t register that anything changed and won’t update. There are a few ways around that, like forcing the update cycle to run or wrapping your javascript with Angular services, but whenever possible you want to keep non-Angular frameworks out of your code.

The following image might seem a little complex right now, but it will be good to keep it in the back of your mind. This shows the basic cycle Angular has when dealing with displaying data on the DOM and knowing when to run it’s internal $digest cycle.
AngularJS $digest cycle
Angular attaches itself to the DOM’s native event loop. The event queue is a process your browser is constantly executing which runs javascript functions. When the visitor’s page loads, Angular adds a function onto the event queue to execute it’s $apply function. Angular’s $apply(function) executes checking all binding and updating the $scope and DOM as needed, and then adds itself to the end of the event queue to be run again. This means Angular’s $apply() function is being executed a number of times per second (unless you clutter the event queue with outside javascript).

Implementing Angular’s $http Service

First, let’s start by creating a new application using the pattern we have been working with:

%MINIFYHTMLbab1a639d4850111612708c25f9bf37518%%MINIFYHTMLbab1a639d4850111612708c25f9bf37519%

If you take a look at inside our javascript where we declare our application controller MyController you’ll notice the function has our $scope parameter. This is where we are going to place the reference to the $http service. By doing this, we’re telling Angular we want it to resolve the reference using the $http service object. Angular does this by using dependency injection.

app.controller("myController", function($scope, $http) {
    		
});

We are now ready to start utilizing the $http service object inside our controller. $http service is able to perform all HTTP methods (Get, Post, Put, Delete, etc…). For this example, we’re going to use the .get method built into the $http service.

Looking at the Angular API documentation for the .get method, we can see it has two parameters. The first is the URL which is required, and the second is an optional config parameter. The optional config parameter is used to do things like modifying the method headers, or in the case of .post (Links to an external site.) send data. For now, we’re going to use a simple Get with no configuration options. W3Schools.com has a public endpoint available for us to use at https://www.w3schools.com/js/js_json_sql.asp. If you visit the link, you’ll notice the data being displayed is in a JSON format. JSON is the default format the $http methods expect back. If you’re connecting to a web service that returns XML, you can declare that the response data is of XML format inside the optional config parameter.

To retrieve the JSON data from https://www.w3schools.com/js/js_json_sql.asp we’ll need to add the following code inside our controller:

$http.get("https://www.w3schools.com/js/js_json_sql.asp");

Now that we have that code inside our controller, we’re still missing a few key additions to consume that JSON data and do something with it.

To start things off, we’ll need to attach a success condition to the .get request.

app.controller("myController", function($scope, $http) {
	$http.get("https://www.w3schools.com/js/js_json_sql.asp")
		 .success(function(data)
		 {
			$scope.Customers = data;
		});
});

By doing so, we’re telling Angular that once .get has successfully received it’s information execute this function by passing the received information into the data parameter. We then take that data variable and place it’s information into the $scope object’s Customers property.

We could stop here. We’ve successfully retrieved the information from our URL endpoint and saved it into our $scope. However, what happens when the web service is However, what happens when the web service not accessible (e.g. due to maintenance)? Instead of a successful response, our .get method will have an error response and the visitor will have no idea why the information was never retrieved.

To inform the visitor that there was an error retrieving the information, we’re going to attach an error condition to the .get request.

app.controller("myController", function($scope, $http) {
	$http.get("https://www.w3schools.com/js/js_json_sql.asp")
		 .success(function(data)
		 {
			$scope.Customers = data;
		 })
		 .error(function(data)
		 {
			alert('There was an error getting the Customers list');
		 });
});

Now that we have the customer data attached to our $scope we can use the ngRepeat directive from earlier to output a list of customers onto our page.

%MINIFYHTMLbab1a639d4850111612708c25f9bf37520%%MINIFYHTMLbab1a639d4850111612708c25f9bf37521%

Customers

NameCityCountry
{{customer.Name}}{{customer.City}}{{customer.Country}}

Conclusion

And there you have it. You now possess enough tools to begin transforming a static website into a highly dynamic one.


Next Steps

Review our case studies and engagements where we helped companies just like yours solve a variety of business needs.


About Oakwood

Since 1981, Oakwood has been helping companies of all sizes, across all industries, solve their business problems.  We bring world-class consultants to architect, design and deploy technology solutions to move your company forward.   Our proven approach guarantees better business outcomes.  With flexible engagement options, your project is delivered on-time and on budget.  11,000 satisfied clients can’t be wrong.

Like what you've read? Please spread the word!

Leave a Reply

Your email address will not be published. Required fields are marked *