In this post we will see how to fetch data from a JSON file in angularjs. We will use the ‘$http’ service to get the data and make use of ‘$q’ to return a promise.

Why do we need ‘promise’ to fetch data? So that we can control the flow of our program in a sane manner. For example, if we make a ‘http’ call without using a promise, JS will not wait for the ‘http’ call to be complete. It will just move on to the next line of code and if that line is a ‘return’ statement then it will return ‘undefined’. But with a promise, you tell JS to wait here till the ‘http’ call is complete cause I have a promise to full fill 🙂 .

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

As always let’s start by adding the required files.

Folder Structure

Data In JSON file

Data In JSON file

We have added three files under ‘dataInJsonFile’ folder. We have also added a new folder called ‘data’ that contains our JSON file.

Next we have to make few changes to ‘index.html’ and ‘appModule.js’. First up ‘index.html’

index.html

Changes that we have made :

  • First we add a link to the third ‘li’ – ‘Data In A JSON File'(‘/datainjson’ is the third route we will define).
  • Finally we add two more scripts files – ‘dijController.js’, ‘dijService.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 ‘dataInJsonCntrl’.
  • Next we define our third route ‘/datainjson’.
  • Lastly we tell angular what html file to use for the view and the controller to be used for this route.

Fetch data from a json file

First up HTML.

dataInJson.html

The HTML strucutre remains the same as the last two posts Data In Controller and Data In Service. Next let’s have a look at the controller.

dijController.js

So what’s going on here? let’s see

  • We tell angular that this module is called ‘dataInJsonCntrl ‘.
  • Then we add a controller to this module, we call this controller ‘dijCntrl’.
  • We are injecting ‘dijService’ service as a dependency in this controller(we will look at the service in a moment).
  • We are using ‘then’ to tell angular that only after you get a response from the service perform the actions in the anonymous function. In our case assign ‘respone.data’ to ‘charJson’.

And now the service file.

dijService.js

Let’s understand what is going on here :

SiteLock