Monday, September 8, 2014

AngularJS Extracting factories and directives to separate modules using method chaining.

init order :
ngRoutes, factories, controllers, directives

index.html

<html ng-app="countryApp">
  <head>
    <meta charset="utf-8">
    <title>Angular.js Example</title>

    <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.10/angular.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.10/angular-route.min.js"></script>

    <script src="countryControllers.js"></script>
    <script src="countriesFactory.js"></script>
    <script src="countryDirective.js"></script>
    <script src="app.js"></script>
  </head>
  <body>
    <div ng-view></div>
  </body>
</html>


app.js

var countryApp = angular.module('countryApp', [
  'ngRoute', // system module
  'countryControllers', // my sepatated modules
  'countriesFactory',
  'countryDirective'
]);

countryApp.config(function($routeProvider) {
  $routeProvider.
    when('/', {
      templateUrl: 'country-list.html',
      controller: 'CountryListCtrl'
    }).
    when('/:countryId', {
      templateUrl: 'country-detail.html',
      controller: 'CountryDetailCtrl'
    }).
    otherwise({
      redirectTo: '/'
    });
});


countriesFactory.js

angular.module('countriesFactory', [])
       .factory('countries', function($http){
  return {
    list: function (callback){
      $http({
        method: 'GET',
        url: 'countries.json',
        cache: true
      }).success(callback);
    },
    find: function(id, callback){
      $http({
        method: 'GET',
        url: 'country_' + id + '.json',
        cache: true
      }).success(callback);
    }
  };
});


countryControllers.js

var countryControllers = angular.module('countryControllers', []);

countryControllers.controller('CountryListCtrl', function ($scope, countries){
  countries.list(function(countries) {
    $scope.countries = countries;
  });
});

countryControllers.controller('CountryDetailCtrl', function ($scope, $routeParams, countries){
  countries.find($routeParams.countryId, function(country) {
    $scope.country = country;
  });
});


countryDirective.js

angular.module('countryDirective', [])
       .directive('country', function(){
  return {
    scope: { country: '=' },
    restrict: 'A',
    templateUrl: 'country.html',
    controller: function($scope, countries){
      countries.find($scope.country.id, function(country) {
        $scope.flagURL = country.flagURL;
      });
    }
  };
});

No comments: