Tutorials for web designers and developers
Tutorials for Developers_

Tutorial 6: Using AngularJS service | Reading JSON file

AngularJS service

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:

    Code 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 :
    var nameSpace = angular.module("GuitarApp", []);
    
    nameSpace.controller("GuitarFunction", ['$scope','$http', function($scope, $http)
    		{    
    			$http.get('js/data.json').success (function(data){
    				$scope.guitarVariable = data;
    		});
    
    		}]
    );

    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.

Download Complete code

Hope you like it. Please share my work.

next-AngularJS MVC
Previous-Chapter-Button

Share on facebook
Share on twitter
Share on linkedin
Share on whatsapp
Share on email

134 Responses

    1. 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}

    2. 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…

    1. 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}

    2. 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…

  1. 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??

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

      1. 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??

      2. 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

      1. 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??

  2. 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??

    1. 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.

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

  3. 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??

    1. 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.

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

  4. 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???

  5. 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???

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

      2. 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

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

  6. 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???

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

      2. 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

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

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

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

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

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

      1. 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?

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

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

      4. 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

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

      1. 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?

      2. 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

  12. 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

  13. 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

  14. 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

  15. 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?

  16. 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?

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

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

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

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

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

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

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

  23. 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

  24. 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

  25. 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.

  26. 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.

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

      1. 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;

        });

  27. 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.

      1. 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;

        });

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

    1. 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).

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

    1. 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).

      1. 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 ,

  30. 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.

  31. 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.

  32. 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.

  33. 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.

  34. 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!

  35. 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!

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

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

Leave a Reply

Your email address will not be published.