requirejs 与 angular - 不解决控制器与嵌套路由的依赖关系

requirejs with angular - not resolving controller dependency with nested route

当路由为多个级别时,RequireJS 无法正确解析依赖关系,如 http://www.example.com/profile/view。如果我只有 http://www.example.com/view,则控制器依赖性已正确解析。

我的bootstrap.js

require.config({
    baseUrl : 'res/js',
    paths: {
        routeResolve: 'routeResolve',
        'domReady': 'lib/domReady',
        angular: 'lib/angular',
        angularRoute: 'lib/angular-route',
        angularResource: 'lib/angular-resource',
        angularSanitize: 'lib/angular-sanitize',
        cssPath : '../css'
    },
    map: {
      '*': {
        css: 'lib/require-css/css.min'
      }
    },
    shim: {
        'angular': {'exports': 'angular'},
        'angularRoute': {deps : ['angular']},
        'angularResource': {deps : ['angular']},
        'angularSanitize': {deps : ['angular']}
    },
    priority: ['angular']
});

文件夹结构:

-rootdir
    - public
          - res
              - js
              - css

当我使用此路由http://www.example.com/profile/view时,所有依赖模块都以url为基础解析为http://www.example.com/profile/res/js/controller.js,该路径http://www.example.com/profile中不存在。

如果我将路由更改为 http://www.example.com/view(仅一级),依赖关系将通过此基础解决 url http://www.example.com/res/js/controller.js

应该是我遗漏了配置问题,但我找不到解决方案。

我创造了working plunker here. It is based on the answer to angular-ui-router with requirejs, lazy loading of controller。我希望这个问题与 HTML 设置 <base href...

有关

有一个状态示例,在 resolve 中通过 requireJS 延迟加载控制器:

$stateProvider
  .state("first", {
    url: "/firstr",
    template: "<div>The message from ctrl: {{message}}</div>",
    controller: "FirstCtrl",
    resolve: {
      loadOtherCtrl: ["$q", function($q) {
        var deferred = $q.defer();
        require(["FirstCtrl"], function() { deferred.resolve(); });
        return deferred.promise;
      }],
    },
  });

那个例子有main.js:

var cfg = {

    baseUrl: "res/js/",

    // alias libraries paths
    paths: { 

        // here we define path to NAMES
        // to make controllers and their lazy-file-names independent

        "TopMenuCtrl": "Controller_TopMenu", 
        "ContentCtrl": "Controller_Content", 
        "OtherCtrl"  : "Controller_Other",  
        "FirstCtrl"  : "Controller_First",
        "app"  : "../../app",  
    }, 

    deps: ['app'] 
} 

require.config(cfg);  

想到这里最重要,因为:

$locationProvider.html5Mode({enabled: true});

base中index.html的设置:

<script>
  var urlBase = document.location.pathname;
  document.write('<base href="'+ urlBase +'" />')
</script>

因为我需要在这里确保它能在 plunker 中工作,所以我会动态生成它,但在你的情况下,它可能只是 <base href="/" /> 或其他一些设置,这将 "teach" 全网搜索资源

检查一下here in action. Read more here