2014년 12월 29일 월요일

[AngularJS] How to pass Factory to Controller through $routeProvider.when {} statement

Hi Experts

I am using 

.config(function($routeProvider, $locationProvider) { }

I am passing the 
    templateUrl: 'chapter.html',
    controller: 'ChapterController'

but i do not know how to pass factory on which ChapterController is dependent.
I know through resolve attribute, i can pass the factory to ChapterController.
but what is the correct syntax.


Any help will be appreciated.

See the sample below. 


(function(angular) {
  'use strict';
angular.module('ngRouteExample', ['ngRoute'])

.factory('grettingTokenFactory',function() {
 var factory: {};
 factory.getText(){
 return 'Hello world'
 }
 return factory;
})


 .controller('BookController', function($scope, $routeParams) {
     $scope.name = "BookController";
     $scope.params = $routeParams;
 })

 .controller('ChapterController', function($scope, $routeParams, grettingTokenFactory) {
     $scope.name = "ChapterController";
     $scope.params = $routeParams;
     $scope.greetings = grettingTokenFactory.getText();
 })

.config(function($routeProvider, $locationProvider) {
  $routeProvider
   .when('/Book/:bookId', {
    templateUrl: 'book.html',
    controller: 'BookController',
    resolve: {
      // I will cause a 1 second delay
      delay: function($q, $timeout) {
        var delay = $q.defer();
        $timeout(delay.resolve, 1000);
        return delay.promise;
      }
    }
  })
  .when('/Book/:bookId/ch/:chapterId', {
    templateUrl: 'chapter.html',
    controller: 'ChapterController'
    
  });

  // configure html5 to get links working on jsfiddle
  $locationProvider.html5Mode(true);
});
})(window.angular);


댓글 없음:

댓글 쓰기