So far we’ve made AngularJS apps by adding data to a controller, and then displaying it in a view.

But what happens when the data contains hundreds of items, or if it’s constantly changing like weather or financial data? Hardcoding data into a controller won’t work anymore.

A better solution is to read the live data from a server. We can do this by creating a service.



In the browser frame on the right, visit https://content.codecademy.com/courses/ltp4/forecast-api/forecast.json. It’s a JSON object containing a city_name and an array days containing weather data for the next five days.


Create a service named forecast that fetches the weather data from the server. In the new file js/services/forecast.js. Type in this code exactly as you see here:

app.factory('forecast', ['$http', function($http) { return $http.get('https://content.codecademy.com/courses/ltp4/forecast-api/forecast.json') .success(function(data) { return data; }) .error(function(err) { return err; }); }]);

Include js/services/forecast.js in index.html in line 61 as a new <script> element.


In the controller, modify MainController by passing in the forecast service, like this:

app.controller('MainController', ['$scope', 'forecast', function($scope, forecast) { // ... }]);

Inside MainController, use the forecast service to save the weather data into $scope.fiveDay, like this:

forecast.success(function(data) { $scope.fiveDay = data; });

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?