How might I move AngularJS Routes into separate fi

2019-03-09 17:07发布

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.

3条回答
爷的心禁止访问
2楼-- · 2019-03-09 17:17

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) {
  ...
});
查看更多
别忘想泡老子
3楼-- · 2019-03-09 17:25

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.

查看更多
叼着烟拽天下
4楼-- · 2019-03-09 17:28

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
查看更多
登录 后发表回答