Creating and Using Angular JS Services


Jim Cooper, experienced Angular JS trainer

Welcome to Part 3 of this review of the Pluralsight course Angular JS Fundamentals by Joe Eames and Jim Cooper. This module is presented by Jim Cooper.

Jim is a software developer at Pluralsight, with more than 20 years of software development experience.

He has a passion for Agile processes, especially lean software development, and has been developing production Angular apps since before v1.0.

Jim has over 10 years of TDD and pair programming experience.

Also in this series:

Part 1: Angular JS Fundamentals
Part 2: Angular Controllers & Markup

Creating and Using Angular JS Services

This module is a fairly in-depth guide to Angular JS Services taking 1 hour and 23 minutes. If you just want a very quick introduction to Angular JS Services, see the module from Scott Allen which is just 35 minutes long.

Introduction to Angular Services

Jim says the term “service” is overloaded! With Angular JS, we mean a worker object that performs business logic.

He explains several good reasons for using Angular JS Services:

Quiz questions:

  • True or False: In Angular, the term “Service” refers to an over-the-network service like a RESTful service
  • Why do we need Services?
  • How is an Angular JS Service different than any other service?

Creating Your First Custom Service

We pick up the Event Registration website where Joe left it at the end of the previous module.

There is a lot of event data in our controller. Jim moves it out into a service in EventData.js

We see the error:

Error: Unknown provider: eventDataProvider

To fix this we simply go to the HTML file and include EventData.js.

Another Custom Service Example

We start by creating a new EditProfile.html page, and you can find this HTML at

Download it and go to DemoApp/app/EditProfiles/Original to find it.

We also see EditProfileController.js and you won’t want to manually type out the regex so grab it from the GitHub repo. The regex acts on a string and checks that it is an email address.

If its not an email address it returns a default gravatar url, otherwise it creates an MD5 hash of the email address and uses that as part of the URL.

We take all of the complex logic out of here and move it into a GravatarUrlBuilder service.

Introduction to Built-In Angular Services

This module covers a lot of Built-In Angular Services:

Jim says the following services aren’t used very often and will only be mentioned briefly:

In Scott Allen’s course he has an example of using the $log service for debugging. We also see an example in the next lesson.

The final group of services that Jim lists is:

Using Angular’s $http Service

So we’ve been hardcoding all the event data up to now. In a real world application, this would be served from another machine, such as a database server.

Here we change EventData.js to fetch the data by using the $http service. We call GET for the url ‘/data/event/1’ and write success and error callback functions.

We use the $log service here to log a warning when the $http service returns an error.

Updating a Node Server for JSON Requests

Jim shows us the Express code we need to serve up the event data. This involves using the body-parser middleware.

In the interests of simplicity, the JSON is read off of a text file, and you can find all four JSON files in the GitHub repository.

For further details on using Node and Express see Jonathan Mill’s course Building Web Applications with Node JS and Express.

Updating an IIS Server for JSON Requests

Jim says this is more difficult than with Node JS, but not too hard.

We create a Web API project, with an EventController and a method for processing GET requests and POST requests.

We also update our default route in WebApiConfig.cs removing the “api/” for shorter URLs.

Again we serve the JSON from disk to keep things simple.

Using $http Promises

Jim says there’s a better way to handle success and error responses than our current implementation with callback functions.

We remove almost all the code from EventData.js and in EventController.js we call the .success and .error methods on the promise.

We include the $log service in our controller for logging the error message and see this working.

The app works the same as before, but is a bit neater.

Using Angular’s $resource Service

This is similar to $http but it assumes we are using a RESTful architecture.

To use this feature we must remember to include angular-resource.js in our app.

There is a promise object, $promise, on the returned object and we can acccess the then and catch methods  via $promise.

Saving Data with $resource

In EventData.js we add a save method and we call this method from EditEventController.js.

The quiz questions are:

  • Which service would be the best fit for accessing a RESTful web service?
  • Which service would be the best fit for accessing a non-RESTful web service?
  • In which module does $resource reside?

Using Angular’s $anchorScroll Service

Jim starts by adding an id attribute to every session list item.

Then he adds a Scroll button to the top of the page and this has an ng-click attribute on it which calls our $anchorScroll service.

We see this scrolls down to the appropriate part of the page as specified by the ID at the end of the URL.

There are two hash symbols (##) in the URL because we don’t yet have HTML5 routing enabled, but this will be covered in the routing module.

Using Angular’s $cacheFactory Service

We start with a CacheSampleController.js file and a CacheSample.html page.

We create a service called ‘myCache’ which uses $cacheFactory and has a capacity of 3, limiting the size of the cache to three items.

In the controller we add three functions:

  • addToCache
  • readFromCache
  • getCacheStats

We add HTML for input boxes and an “Add to Cache” button.

This program adds key value pairs into a cache. When we hit our capacity limit, the oldest entry is removed to make room for the latest one.

Using Angular’s $compile Service

Jim says the compile services is often used internally in Angular JS, whenever a page is loaded.

The compile service is used to look for directives and process them.

We typically use the compile service inside a directive. The directives module is later on in this course, so here we see an example of using $compile without any directives.

We see the error:

Error: [$parse:isecdom] Referencing DOM nodes in Angular expressions is disallowed!

This is Angular trying to prevent us from an injection attack. So Jim recommends against using $compile like this.

Using Angular’s $parse Service

Jim says this is quite similar to the $compile service and also used internally by Angular when processing a page.

It evaluates an expression and turns it into a function that can be evaluated against a given context. We see a simple ‘1 + 2’ example here.

Jim warns again that we typically would not use this, and if we do use it we should probably use it inside a directive.

Using Angular’s $locale Service

This is used for localization of date-time and numeric formats.

We see that we can set it to long date format (Friday, June 26, 2015) and short date format (6/26/15).

To change the localization we use one of the localization files found for example at (change this URL for the latest version).

Jim chooses the Spanish localization file angular-locale_es.js and adds a reference for that. We see the date as:

viernes, 26 de junio de 2015

Using Angular’s $timeout Service

Jim says this is like JavaScript’s setTimeout but with some important differences.

We see an example with John Doe appearing after 3 seconds. The main difference is the use of a promise allowing us to cancel the timeout.

Jim creates an input with the ng-model attribute on it, and he discusses when are where Angular reevaluates the model bindings.

This topic is also covered by Scott Allen in his Angular JS Services module.

The quiz questions are:

  • Which service would you use to display localization based date-time or numeric formats?
  • Why would you use $timeout vs. setTimeout?
  • Which service does Angular use internally to process a page and handle directives on the page?

Using Angular’s $exceptionHandler Service

Sometimes we might want to handle Angular exceptions ourselves. In these cases, we should use $exceptionHandler

We actually overwrite $exceptionHandler with our own logic here, and in this example we just log the exception to the console.

Using Angular’s $filter Service

This gives us access to any filter, whether that be a custom one or one of the built-in filters.

The example that we see outputs a textual descriptions of each duration.

Jim says we don’t actually need to use $filter because we can just inject the filter(s) that we want.

Using Angular’s $cookieStore Service

According to the official documentation, this service has been deprecated and we should use $cookies instead.

In this lesson Jim imports angular-cookies.js and shows us a Cookie Store sample page with the following buttons:

  • Store Cookie
  • Get Cookie
  • Remove Cookie

Overview of Less Common Angular Services

The services that Jim says aren’t often used are:


We see examples and hear explanations of these services in this lesson. Jim says it is bad practice to use the last three services.

There are also a few other services which are covered in the Routing and Testing modules of this course.

The quiz questions:

  • Which service would you modify if you want to change the {{ }} expression delimiters?
  • How many root scopes are there in an application?
  • Can child scopes access items on the root scope?


Suggested Exercises

The first suggested exercise is:

Update the save method of the eventData service to lookup next eventId by finding the highest event id of all existing events and incrementing by one (instead of just setting it to 999).

This lesson also describes three other exercises for you to try which should fortify your Angular JS Services skills.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s