How might I move AngularJS Routes into separate fi

2019-03-09 16:40发布

问题:

I was curious if anybody was familiar with separating routes from the main app config function. My route list is getting quite large and I wanted to move them into a separate file and load them into the main config. I have seen this done before but I cannot remember or find where I saw it. Any help would be appreciated.

回答1:

You can (and should !) use AngularJS modules to separate your application into modules.

Then, each module can define its own routes (with its own .config). Then, in your main module (usually "app"), you just need to require them as dependencies and you're set to go.

angular.module('blog', ['ngRoute'])
  .config(['$routeProvider', function ($routeProvider) {
    ...
  }];

angular.module('app', ['blog', 'user']);

Then you can have each module in its own file.



回答2:

You can put your config function in a separate file easily:

App-config.js

   angular.module('app').config(function(...){...});

Just make sure you include the module definition before you include App-config.js.

App-module.js

  angular.module('app',[...]).controller(...).etc


回答3:

It's easy to set up config file separately. There are few other ways to set this up, and I played around with those structure for config; this seems to work for me the best. Enjoy!

---> myApp.html

<html lang="en" ng-app="myApp">
    <head>
           <script src="lib/angular.min.js" type="text/javascript"></script>
           <script src="lib/angular-route.min.js" type="text/javascript"></script>
           <script src="js/app.js" type="text/javascript"></script>
           <script src="js/controller.js" type="text/javascript"></script>
           ...
        </head>
        <body ng-controller="MainCtrl">

             <!-- /* Using ng-view with routeProvider to render page templates */ -->
            <div data-ng-view></div>

    </body>
</html>

----> app.js

'use strict';

angular.module('myApp', [
    'ngRoute',
    'ngAnimate',
    'myApp.controllers'
]).
config(['$routeProvider', function ($routeProvider) {     
    $routeProvider.when('/page1', {
        templateUrl : 'partials/page1.html',
        controller : 'page1Controller'  
    });

    $routeProvider.when('/page2', {
        templateUrl : 'partials/page2.html',
        controller : 'page2Controller'  
    });

    $routeProvider.when('/images', {
        templateUrl : 'partials/page3.html',
        controller : 'page3Controller'
    });

    $routeProvider.otherwise({redirectTo: '/page1'});
}]);

--->controller.js

angular.module('myApp.controllers', ['myModules'])

.controller('mainCtrl', function($scope) {
  ...
})

.controller('page1', function($scope) {
  ...
})

.controller('page2', function($scope) {
  ...
})

.controller('page3', function($scope) {
  ...
});