refactor large AngularJS module config into separate files

前端 未结 3 1528
傲寒
傲寒 2020-12-15 19:53

Problem: Large config()

The config of my AngularJS app is growing quite large. How would you refactor the following into separate files?



        
3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-15 20:59

    I just did this recently with a provider.

       angular.module('EventView')
    .provider('routing', ['$stateProvider', '$urlRouterProvider',
        function($stateProvider, $urlRouterProvider) {
            this.init = function() {
                // For any unmatched url, redirect to /home
                $urlRouterProvider.otherwise('/home');
    
                // Now set up the states
                $stateProvider
                    .state('login', {
                        url: '/account/login?{redirectUrl}',
                        controller: 'loginCtrl',
                        templateUrl: 'partials/account/login/login.tpl.html'
                    })
            }
    
            // has to be here
            this.$get = function() {
                return {};
            };
        }
    ]);
    

    In the config you can just call the function.

    angular.module('EventView').config(['routingProvider', function (routingProvider) {
            routingProvider.init();         
        }
    ]);
    

    There are two gotachas, first that the name of the provider adds provider to it when you reference from the config and the second is that you have to implement the $get and return a function.

    Good luck!

提交回复
热议问题