问题
The RequireJS
is not resolving dependency properly when the routes is of multiple levels as in http://www.example.com/profile/view
. If I just have http://www.example.com/view
, the controller dependency is resolved properly.
My 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']
});
Folder structure:
-rootdir
- public
- res
- js
- css
When I use this route http://www.example.com/profile/view
, all the dependency modules are resolved with base url as http://www.example.com/profile/res/js/controller.js
, which does not exist in this path http://www.example.com/profile
.
If I change the route to http://www.example.com/view
(just one level), dependencies are resolved with this base url http://www.example.com/res/js/controller.js
There should be a configuration issue which I am missing, but I could not find a solution for this.
回答1:
I created working plunker here. It is based on the answer to angular-ui-router with requirejs, lazy loading of controller. I would exepct that the issue will be related to HTML setting <base href...
There is an example of the state, which in resolve
loads lazily controller via 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;
}],
},
});
There is the main.js for that example:
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);
The most important think here, because of the:
$locationProvider.html5Mode({enabled: true});
is the setting of the base
in the index.html:
<script>
var urlBase = document.location.pathname;
document.write('<base href="'+ urlBase +'" />')
</script>
Because I need here to be sure that this will work in plunker I do generate that dynamically, but in your case it could be just <base href="/" />
or some other setting, which will "teach" all the web where to search for resources
Check it here in action. Read more here
来源:https://stackoverflow.com/questions/28188196/requirejs-with-angular-not-resolving-controller-dependency-with-nested-route