How to load remote data using angularjs?

In this tutorial, we will learn how to load remote data using angularjs application.

Live demo can be seen here:

Load Json File with AngularJS

Let's create an index.html file with following contents:

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>AngularJS 1</title>

    <!-- cdn for ootstrap Links for css -->
    <link rel="stylesheet" href="https://maxdata.bootstrapdata.com/bootstrap/3.3.7/css/bootstrap.min.css" />

    <!-- Custom Stylesheet -->
    <link rel="stylesheet" href="app.css" />

    <!-- cdn for angularjs -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.js"></script>

    <!-- AngularJS Custom Modules -->
    <script src="./app.js"></script>
    <script src="./phone-list/phone-list.js"></script>
</head>
<body ng-app="phoneListApp">
    <div class="container">
        <phone-list></phone-list>
    </div>
</body>
</html>

Update component file

Let's make some changes to our existing phone-list/phone-list.js file shown below:

// define phoneList module
 angular.module('phoneList', []);

 // component
 angular.
    module('phoneList').
    component('phoneList', {
    templateUrl: './phone-list/phone-list.html',
    controller: function PhoneListController($http) {
        var self = this;
        $http.get('./phone-list/phone-list.json').then(function(response) {
            self.phones = response.data;
        });
    }
 });

Let's understand our code, AngularJS's $http service will be injected in our controller function.

Using $http.get function we will load our remote json files and update our view with corresponding data. Let's take a look at our sample json file:

[
  {
    "name": "Motorola XOOM\u2122 with Wi-Fi"
  },
  {
    "name": "MOTOROLA XOOM\u2122"
  },
  {
    "name": "MOTOROLA ATRIX\u2122 4G"
  },
  {
    "name": "Dell Streak 7"
  },
  {
    "name": "Samsung Gem\u2122"
  },
  {
    "name": "Dell Venue"
  },
  {
    "name": "Nexus S"
  }
]

That is it, we have successfully replaced hard coded phone array with remote json file contents using $http service provided by angularjs by default.

What did we learn today?

  • how to inject service to controller
  • $https service to make remote calls and fetch json data

Related Posts