Saturday, March 15, 2014

Using Angular.js Factories to Get Remote Data

In this post, I’d like to show the differences between using an Angular.js factory to get local JSON data vs remote data via an AJAX call.

For this example, I’m assuming that we have a JSON dataset that describes different types of fruit, for example:

1
2
3
4
5
6
7
8
9
10
11
12
{
  "fruits": [
    {
      "id": "1",
      "name": "Apple"
    },
    {
      "id": "2",
      "name": "Orange"
    }
  ]
}


At it’s simplest, an Angular.js view to iterate over this data could look like the following HTML

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!doctype html>
<html lang="en" ng-app="fruitsApp">
<head>
<title>Angular Sample App</title>
<script src="app.js"></script>
</head>
 
  <body>
    <div ng-controller="fruitsController">
      <ul>
        <li ng-repeat="fruit in fruits"></li>
      </ul>
    </div>
  </body>
</html>

A Hardcoded Angular.js Controller and Factory


In the HTML view, we can see that an Angular.js controller called fruitsController is being used within a module called fruitsApp. We’re then using ng-repeat to iterate through a collection of fruit and add them into a simple HTML list.

If we wanted to get data locally rather than via HTTP, we could declare a controller and factory as follows:


1
2
3
4
5
6
7
8
9
10
11
12
13
var fruitsApp = angular.module('fruitsApp', [])
 
fruitsApp.factory('fruitsFactory', function() {
  return {
    getFruits: function() {
      return  [{"id": "1","name": "Apple"}, {"id": "2","name": "Orange"}];
    },
  };
});
 
fruitsApp.controller('fruitsController', function($scope, fruitsFactory) {
  $scope.fruits = fruitsFactory.getFruits();
});
This is a very simple controller and factory. The fruitsController returns a view model which is populated from the fruitsFactory, which simply has a hardcoded static list of fruit.

A Dynamic Angular.js Controller and Factory Using AJAX

The above exampe will work for getting data, but isn’t of much use for dynamically generated content. For dynamic content, we need to make an HTTP request to get our data, for example via a REST call.

To make a HTTP call via an Angular.js factory, we need to pass the $http object into the factory and then make a call to the remote HTTP request using the $http.get() method.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var fruitsApp = angular.module('fruitsApp', [])
 
fruitsApp.factory('fruitsFactory', function($http) {
  return {
    getFruitsAsync: function(callback) {
      $http.get('fruits.json').success(callback);
    }
  };
});
 
fruitsApp.controller('fruitsController', function($scope, fruitsFactory) {
  fruitsFactory.getFruitsAsync(function(results) {
    console.log('fruitsController async returned value');
    $scope.fruits = results.fruits;
  });
});

In this example, you can see that the controller makes a request to the factory which then calls an asynchronous function ($http.get) to get the data. When this asynchronous function completes successfully, it calls back to an anonymous function in the controller and populates the view model.

No comments:

Post a Comment