Fetching data in angularjs can be done in a number of ways… should I use controller or service or hang on there is something called resolve! So many options can be confusing when you are starting out. In this series, I will try to explain a few ways to go about fetching data in angularjs(JSON data).

Here is what we will cover in this series (fetching data in angularjs).

Our folder structure will be as follows :

Folder Structure

Folder Structure

Each of the topic covered will be a module, each module will be a sub folder inside the modules folder. Each module folder will have all the files related to it.

appModule.js is our main app file. Here we define all our routes and the templates & controllers for these routes.

index.html is our main html file.

Let’s start with index.html :

Simple, our app is named ‘fetchDataApp’. We have a list with all the modules we will be writing. Each element in this list will be a link. Clicking on a link should change the view in the div below.

Now appModule.js :

On line one, we are specifying the name of our app ‘fetchDataApp’. Then we tell angular that our app will use ngRoute and dataInControllerCntrl (this is the controller for our Data in controller module).
We use config to define our routes. Our first route is for Data in controller and called ‘dataincontroller’. We also tell angular what template and controller to use for this route.

That’s about it for now. We will keep updating ‘index.html’ and ‘appModule.js’ every now and then to add new controllers and service. For now lets move to our first module.

Data in controller

It’s not a good idea to have any kind of data in the controller, but for the sake of this post let’s assume you have some data(JSON) in your controller and you want to display it using the view.

Let’s get straight to the controller :

First we tell angular this module is called ‘dataInControllerCntrl’. We then add a controller to the module, this controller is called ‘dicCntrl’. This controller has one JSON object ‘charJson’ added to it’s scope. That’s all there is to the controller, everything else is handled in the view using some angular magic. Let’s have a look at our view.

We let angular’s ‘ng-repeat‘ directive perform it’s magic. Just tell ‘ng-repeat‘ the variable that holds the data, what you want to show & how, and it will take it from there. If you look attentively ‘charId’, ‘charName’ and ‘charTitle’ are all keys from our JSON.

That’s all good, how does it work?

  • We have added ‘charJson’ to the controller scope.
  • While defining the route we have told angular which controller goes with the view.
  • So the view knows which controller is attached to it.
  • This is how it knows about ‘charJson’
  • After that ‘ng-repeat‘ takes over.

Get complete code on github

SiteLock