AngularJS service

Tutorial 6: Using AngularJS service | Reading JSON file

In AngularJS by Hafiz Faraz65 Comments

We can access external data by using angularjs service , so far we bringing in data and pasting into a variable called guitarVariable. You probably gonna bring data in a file so it is easier to manage that way. In traditional javaScript you bring in data using XHR request from a JSON file, you probably know that technique as ajax. In angularJS we can access external data by something called a service or angularJS service or $http service in angularjs. An angularjs service is nothing more than a small piece of code that takes care of common tasks like reading from a file. In this case we are interested in a particular service and it is called ‘$http service’. Job of this service is to communicate between http server and your application. It’s pretty easy to use. Lets dig in:

In the previous tutorial 5 you had controllers.js file, (Download previous tutorial files we shall be working on it now) which comprised of model, controller and module (if you don’t know these terms then goto Angularjs MVC Tutorial). we need to make some deletion in controllers.js file.

  1. Delete the data part in controllers.js file so that it looks like this then we shall be able to get data from another file i.e data.json file in JS folder of our project:AngualrJS ServicesCode Explanation:
    • line 1: name of module and a nameSpace variable
    • line 3: variable ‘nameSpace’ is holding a controller named ‘GuitarFunction’ and that controller is a function which WAS holding some data in guitarVariable.
  2. Now you need to make several changes to your controllers.js file like this or simply copy paste following code to controllers.js :
    Code Explanation:

    • Beginning from last line of above code: $scope.guitarVariable is getting a ‘data’ variable which has some value or data
    • moving a line above: $http is service responsible for communicating with other file. $http says get file from ‘js/data.json’ and if the operation is a ‘success’ then execute a function holding the ‘data’ which it got automatically from data.json file
    • A one more line above: [‘$scope’, ‘$http’, function($scope, $http){ … }] is little bit tricky: it takes an array holding two objects one is $scope and other is a service i.e $http. The reason we have this in array is angularJS automatically minifies code which means it removes extra spaces and shorten variable names for faster performance but sometimes this minification causes trouble so we just told controller NOT to minify $scope, $http services and function inside array.
    • thing you might have noticed that function name is gone. We call it function literal or anonymous function which does not have a name. We want to execute it as it is, it is used when we are certain that this set of instructions will execute. This makes code more manageable.
  3. Try running code in firefox NOT in chrome because chrome does not allow local file access due to its policy. If you want to do so then you need WAMP server up and running on your local system so that $http takes your computer as server and gets data.json file accordingly. Then it will seamlessly run in chrome also.
  4. When you run the index.html file it will show the same result as shown in previous tutorial but this time it is reading data from another file (data.json) instead of same controllers.js file.AngularJS Complex Models

Download Complete code

Hope you like it. Please share my work.

next-AngularJS MVC
Previous-Chapter-Button

  • How to change this step:

    $http.get(‘js/data.json’).success (function(data){
    $scope.guitarVariable = data;

    with PHP file in Web Servis.

    need help… 😀

    • Hafiz Faraz Mukhtar

      you can do this by encoding json from php or PHP to json by using JSON function in php.
      json_encode = Returns the JSON representation of a value
      json_decode = Decodes a JSON string
      json_last_error = Returns the last error occurred
      Example:

      The following example shows how to convert an arrays into JSON with PHP:

      1, ‘b’ => 2, ‘c’ => 3, ‘d’ => 4, ‘e’ => 5);
      echo json_encode($arr);
      ?>

      While executing, this will produce following result:

      {“a”:1,”b”:2,”c”:3,”d”:4,”e”:5}

    • junniramey

      To run this in Chrome. Follow these steps
      1: Copy that folder to wamp/www/(yourfolder)
      2: open localhost/yourfolder
      3: open controllers file and Replace that Code

      var nameSpace = angular.module(“GuitarApp”, []);

      nameSpace.controller(“GuitarFunction”, function GuitarFunction($scope,$http){
      $http.get(“js/data.json”).success (function(data){
      $scope.guitarVariable = data;
      });
      }

      );

      Now it will be okay for cross browsers and Localhost Too…

  • Shahzad Ashraf

    i have already install the wamp server…??then how to run my app??

    • Hafiz Faraz Mukhtar

      just copy and paste the app folder in www directory of wamp server and access that wamp server in your browser.

      • Shahzad Ashraf

        i am facing problem in accessing the wamp server in browser??my wamp server is working properly…but when i wrote localhost in url not getting the wamp server??

        • Hafiz Faraz Mukhtar

          that is the problem with you wamp. To fix this : you need to quit skype and try reloading localhost in your browser or alternatively localhost:8080

  • Shahzad Ashraf

    is there any need to put my app folder in directory of wamp folder that www folder..or just need to run the wamp server and them i click the index file??

    • Hafiz Faraz Mukhtar

      Yes it is a good idea to put your app folder in www because this way you can load it in any browser as it is coming from a server. Google chrome will have no difficulty running it locally.

      • meatlover

        Google Chrome has a security policy. Maybe you can try this if you are in windows machine, chrome.exe –disable-web-security

  • Shahzad Ashraf

    brother i have already taken lecturals on angularjs from my uni teacher…he run the code after running the node..but u have not metioned it yet???

    • Hafiz Faraz Mukhtar

      yes because I specifically targeted angularjs only

      • Shahzad Ashraf

        why we use that node.js??

        • Shahzad Ashraf

          will u used it later??becs me facing comfusion either to used it or not

          • meatlover

            NodeJS is another framework that uses Javascript. Don’t bother yourself by learning this too. I just started recently JS, which my background more in Java area

    • Shahzad Ashraf

      in university my sir was using the express framwork with angularjs??why he was using??and u not??

  • Shahzad Ashraf

    if we want to get data from server then how we got from server??

  • Shahzad Ashraf

    in university my sir was using the express framwork with angularjs??why he was using??and u not??

  • Manoj

    sir when i try to get data from data.json file through http service then it not show anything ony my index page

    • Hafiz Faraz Mukhtar

      what is the error in console?

      • Manoj

        no any error but data now display on index page

        • Manoj

          not display

          • Manoj

            please help

          • Hafiz Faraz Mukhtar

            kindly send me screen shot at: http://facebook.com/h.farazmukhtar
            so that I can see what is the issue.

          • Manoj

            ok sir i will send you the screen shot but i just download you tutorial and run it with visual studio 2013 it work ok till i get data from controller but when i try to get data from data.json file then it show empty Search panel only and please just tell me one thing does your tutorial work with asp.net or only with php is it nessary to have installed wamp server in your pc?

          • Shahzad Ashraf

            AoA…is the problem is solved??i am also facing same problem…not getting the data from data.jason file through http service

          • Manoj

            no sir i am trying from last two days but still not get any answer i search so much on net too

          • Shahzad Ashraf

            same the problm is with me…me also stuck off from yesterday..

          • Shahzad Ashraf

            what is your fb id??i want to add you for discussion

        • Hafiz Faraz Mukhtar

          you need to start my project files in firefox because chrome has restriction. Alternatively, you can run this project on running wamp server. This way you will see the data from data.json

  • Shahzad Ashraf

    Important……………sir i am trying to get the data through $http service but me not getting data from file…???its showing nothing…..plz reply me as soon as possible…becs i am stuck here..
    here is index file code

    Guitar App store

    kk

    {{item.name }}
    {{item.description}}

    and controller file is here
    var nameSpace = angular.module(“GuitarApp”, []);

    nameSpace.controller(“GuitarFunction”, [‘$scope’,’$http’, function($scope, $http)
    {
    $http.get(‘js/data.json’).success (function(data){
    $scope.guitarVariable = data;
    });

    }]
    );
    3.jason file is same as your

    • Hafiz Faraz Mukhtar

      problem is at {{item.description}}. you need to enclose it inside .

      • Shahzad Ashraf

        i enclosed it in ..but not show any thing on index page

        • Manoj

          Shahzad what you using to run this code? visual studio or PHP?

          • Shahzad Ashraf

            i am coding in nodepad++…using javascript

  • junniramey

    Hello Faraz.. Have a good day. i have a question.. The Controller is working as too,

    var nameSpace = angular.module(“GuitarApp”, []);

    nameSpace.controller(“GuitarFunction”, function GuitarFunction($scope,$http){
    $http.get(“js/data.json”).success (function(data){
    $scope.guitarVariable = data;
    });
    }

    );
    so what is the basic difference in both the codes? it is relate to performance speed?

    • Hafiz Faraz Mukhtar

      with anonymous function code is well managed and efficient.

  • Dmitri

    It might be helpful to mention that using $http inside a Controller is actually a bad practice. That is resposibility of a Service.

    • Hafiz Faraz Mukhtar

      Yes sir you are absolutely right. I tried to make it simpler for beginners and will surely apply update to this post.

  • Mahesh

    Hi there, What modifications should be done to this in order to retrieve a JSON object from a remote server? 🙂

    • Hafiz Faraz Mukhtar

      for that resource module is used which is for REST.. this way remote files can be accessed.

  • sonali

    hello Sir, lots of thanks for providing this material, I have one question please reply me ASAP
    How to parse JSON file data in angular Js

  • christine

    Can i please know how to make this work this on server. For me json file doesn’t load on server but it works locally.

    • Hafiz Faraz Mukhtar

      well i tested on server as well and it loads json just fine. is that code and file hierarchy same?? kindly share some code.

      • christine

        yes hierarchy is same. but wen i uploaded on live server its not working

        .controller(“aboutCtrl”, [‘$scope’,’$http’, function($scope, $http)
        {

        $http.get(‘json/about.json’).success(function(data){
        $scope.aboutVariable = data;

        });

        • kindly check: blog.hfarazm.com/demo/jsonService/
          its the same code

        • try uploading my files and let me know if my exact code runs there

  • christine

    can i please know why the json file doesn’t load on server but works locally

  • JerryShovan

    so if I am going to reference the data, say as in a parameter in another function, i would reference it as $scope.guitarFunction?

    • Hafiz Faraz Mukhtar

      scope is an “object” that “binds” to DOM element where you apply controller. All child elements can read and modify scope data (unless you modify primitives in new scopes or they’re isolated).

  • Amrendra

    Can any one tell me how to read multiple json file in a folder

    • $http.get(‘js/file1.json’).success (function(data){
      $scope.file1Data = data;
      $http.get(‘js/file2.json’).success (function(data){
      $scope.file2Data = data;

      • Santhu

        I think my qn is real close to this ,i have a case something like this ,

        Controller (….

        $scope.guitarvariables =[{

        json data goes here ;

        }])

        $scope.guitarvariables2 =[{

        json data goes here ;

        }]),

        I would like to put these 2 data sets in same file and get it seperately, would it possible ,

        • yes it is possible. Kindly search JSON format to write multiple datas. it is very simple.

  • hari

    Hi,

    There is no data.json file, so the result is just…..Goto developer’s blog. Could you help me to resolve this issu.

    Thank you,
    Hari.

  • hari

    Could anyone help me to read and write into a json file using ngResource directive?

    file: controller.js

    angular.module(‘ionicApp’, [‘ionic’, ‘ngResource’])

    .factory(‘Post’, function($resource) {
    return $resource(‘/api/post/:id’);
    })

    .controller(‘MainCtrl’, function($scope, Post) {
    // Get all posts
    $scope.posts = Post.query();

    // Our form data for creating a new post with ng-model
    $scope.postData = {};
    $scope.newPost = function() {
    var post = new Post($scope.postData);
    post.$save();
    }
    });

    file: index.html:

    Read and Write into a JSON file using ngResource Directive

    New Post:

    Create

    When I run this project I need to enter data something like “I just ate an apple” then the server should return as

    {

    “text”: “I just ate an apple”,
    “id”: 1
    }

    NOTE: This is related to IONIC project. And I just want to read and write into a JSON file using ngResource directive. For more information, please visit: http://learn.ionicframework.com/formulas/backend-data/

    Would be awaiting.

    Thank you,
    Hari.

  • Bread Crumble

    This was the most straightforward tutorial explaining the use of $http in getting json data. A lot of the other posts out there are unnecessarily too complicated and too much for an angularJS noob like me. Thanks so much!

  • Karthik Sen

    How can i search and display a single item in json file.

  • daffy

    i am unable to load local json file…” $http.get(‘filename.json’)” does not works.
    Can you please help out…. M new to angularjs

  • Cephatech

    Please Any Help for me
    All is working well but if my .json file contain any space it don’t work