AngularJS Framework : Query into a service
Picture from How to structure large angularJS applications
The following sections are largely based on Introduction to Angular.js in 50 Examples (part 2).
We'll start from where we left off (Creating a new service using factory). In the previous sample, we managed to fetch json data only once. Now, in this section, we're going to do a refactoring the code so that we fetch json data only in one place using countries.find() function.
Two of the template files are the same as beforehere (country-list.html and country-detail.html).
Here is our main code (query.html):
<html ng-app="countryApp"> <head> <meta charset="utf-8"> <title>Angular.js Example</title> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular-route.min.js"></script> <script> var countryApp = angular.module('countryApp', ['ngRoute']); countryApp.config(function($routeProvider) { $routeProvider. when('/', { templateUrl: 'country-list.html', controller: 'CountryListController' }). when('/:countryName', { templateUrl: 'country-detail.html', controller: 'CountryDetailController' }). otherwise({ redirectTo: '/' }); }); countryApp.factory('countries', function($http){ return { list: function(callback){ $http.get('countries.json').success(callback); }, find: function(name, callback){ $http.get('countries.json').success(function(data) { var country = data.filter(function(entry){ return entry.name === name; })[0]; callback(country); }); } }; }); countryApp.controller('CountryListController', function ($scope, countries){ countries.list(function(countries) { $scope.countries = countries; }); }); countryApp.controller('CountryDetailController', function ($scope, $routeParams, $http){ countries.find($routeParams.countryName, function(country) { $scope.country = country; }); }); </script> </head> <body> <div ng-view></div> </body> </html>
The rendered output of factory.html is the same as in the example of the previous tutorial.
AngularJS
Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization