路由子模块的角度

时间:2017-04-13 16:12:19

标签: angularjs ngroute

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

我有一个有角度的应用程序,它有不同的模块。我要为每个人写,特定的路由文件,但我有这个错误

  

未捕获错误:[$ 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文件

1 个答案:

答案 0 :(得分:3)

要实现这样的项目结构,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),它们将它们包装到一个角度应用程序中。

$stateProviderui.router提供的服务用于注册状态。

其他信息

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

<强>更新

但是,如果你仍想坚持使用ngRoute,thisthis清楚地解释了如何获得相同的结果。