angular 中的路由子模块

routing sub-modules in angular

不同模块如何写自己的路由?

我有一个 angular 应用程序,它有不同的 modules.i 我打算为每个应用程序编写特定的路由文件,但我遇到了这个错误

Uncaught Error: [$injector:unpr] http://errors.angularjs.org/1.6.4/$injector/unpr?p0=routeServiceProvider%20%3C-%20routeService

这是我的代码:

sample.module.js

angular.module('app.sample', []);

sample.route.js

angular
.module('app.sample')
.run(appRun);

  /* @ngInject */
  function appRun (routeService) {
     routeService.configureRoutes(getRoutes());
  }

 function getRoutes () {
    return [ {
       url: '/sample',
       config: {
          templateUrl: 'sample.html'
       }
     }
    ];
}

我已经添加 ngRoute 并将这些文件注入 index.html 文件

要实现这样的项目结构,ui-router 是最好的方法。它是一个单独的库,因此您必须将其作为依赖项包含到您的项目中。

以下是对您的案例有用的片段

dashboard.module.js

angular.module('app.dashboard', ['ui.router']);

dashboard.router.js

    angular.module('app.dashboard')
        .config(routerConfig);

    routerConfig.$inject = ['$stateProvider'];
    function routerConfig($stateProvider) {
        $stateProvider
            .state('state1', {
                url: '/state1',
                templateUrl: 'url/to/state1.html',
                controller: function () {
                    // controller code here
                }
            })
            .state('state2', {
                url: '/state2',
                templateUrl: 'url/to/state2.html',
                controller: function () {
                    // controller code here
                }
            });
    }

sample.module.js

angular.module('app.sample', ['ui.router']);

sample.router.js

angular.module('app.sample')
        .config(routerConfig);

    routerConfig.$inject = ['$stateProvider'];
    function routerConfig($stateProvider) {
        $stateProvider
            .state('state3', {
                url: '/state3',
                templateUrl: 'url/to/state3.html',
                controller: function () {
                    // controller code here
                }
            })
            .state('state4', {
                url: '/state4',
                templateUrl: 'url/to/state4.html',
                controller: function () {
                    // controller code here
                }
            });
    }

最后,app.module 连接所有这些模块

app.module.js

angular.module('app', [
    /*
     * sub-modules
     */
    'app.dashboard',
    'app.sample'
]);

总而言之,您有两个独立的子模块(app.dashboardapp.sample),它们有自己的路由逻辑和一个模块(app)将它们包装成一个 angular申请.

$stateProvider,由ui.router提供的服务,用于注册状态。

附加信息

由于您的应用程序是模块化的,您可能需要 ui.router 大力支持的嵌套路由。阅读 docs 以获取有关嵌套状态的更多信息。

更新

但是,如果您仍然想坚持使用 ngRoute,this and this 清楚地解释如何实现相同的结果。