In our last post, Fetching Data in Angularjs we saw how to fetch data stored in the controller. This post will show you how to fetch data stored in a service.

This is the second post in a series of posts about fetching data in Angularjs. Here are the topics covered in this series.

First things first, let’s add a ‘dataInService’ sub-folder inside our modules folder. Here are the files we will have inside this folder.

Folder Structure

Data In Service

Data In Service

Before we start we have to make few changes to the ‘index.html’ and ‘appModule.js’ files. Let’s start with the ‘index.html’ file

index.html

Changes to the ‘index.html’ file are :

  • Add a link to the second ‘li’ – ‘Data In Service'(‘/datainservice’ is the second route we will define).
  • Added two more scripts files – ‘disController.js’ and ‘disService.js’.

Next we update the ‘appModule.js’ file.

appModule.js

Here is what is going on :

  • First we tell angular that there is one more module called ‘dataInServiceCntrl’.
  • Next we define our second route ‘/datainservice’.
  • Lastly we tell angular what html file to use for the view and the controller to be used for this route.

Fetch data stored in a service

Let’s start with the HTML.

dataInService.html

If you have read Fetching Data in Angular, you will notice the HTML part is the same. This is because we will be using similar kind of data. Now let’s look at the controller.

disController.js

What’s going on here? let’s see

  • We tell angular that this module is called ‘dataInServiceCntrl’.
  • Then we add a controller to this module, we call this controller ‘disCntrl’.
  • We are injecting ‘disService’ service as a dependency in this controller(we will look at the service in a moment). What is dependency injection? you can read about it here, in the angular docs.
  • Lastly we assign disService to ‘charJson’ which is added to the controller’s scope.

And now the last file that we have look at is our service.

disService.js

Let’s understand what is going on here :

SiteLock