AngularJS service

Tutorial 6: Using AngularJS service | Reading JSON file

In AngularJS by hfarazm134 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

Comments

  1. How to change this step:

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

    with PHP file in Web Servis.

    need help… 😀

  2. How to change this step:

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

    with PHP file in Web Servis.

    need help… 😀

    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…

  3. How to change this step:

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

    with PHP file in Web Servis.

    need help… 😀

    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…

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

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

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

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

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

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

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

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

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

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

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

  11. 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. yes because I specifically targeted angularjs only

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

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

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

  12. 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. why we use that node.js??is it used as sever??like wamp,zamp

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

      1. i enclosed it in paragraph tag p..but not show any thing on index page…

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

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

    1. with anonymous function code is well managed and efficient.

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

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

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

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

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

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

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

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

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

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

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

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

        });

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

        });

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Leave a Comment