nil*_*zen 9 angularjs angular-routing angularjs-controller
是否可以根据路由组动态加载控制器,它的js文件和模板?Psuedo代码不起作用:
$routeProvider.when('/:plugin', function(plugin) {
templateUrl: 'plugins/' + plugin + '/index.html',
controller: plugin + 'Ctrl',
resolve: { /* Load the JS file, from 'plugins/' + plugin + '/controller.js' */ }
});
Run Code Online (Sandbox Code Playgroud)
我已经看到很多类似这样的问题,但是没有基于路由组加载js文件/控制器的问题.
nil*_*zen 15
我成功解决了它的灵感来自@calebboyd,http : //ify.io/lazy-loading-in-angularjs/ 和http://weblogs.asp.net/dwahlin/archive/2013/05/22/dynamically-loading -controllers-和看法,与-angularjs-和requirejs.aspx
使用http://dustindiaz.com/scriptjs
app.js
app.config(function($controllerProvider, $compileProvider, $filterProvider, $provide) {
app.register = {
controller: $controllerProvider.register,
directive: $compileProvider.directive,
filter: $filterProvider.register,
factory: $provide.factory,
service: $provide.service
};
});
Run Code Online (Sandbox Code Playgroud)
然后我注册"按组加载控制器"路由.
$routeProvider.when('/:plugin', {
templateUrl: function(rd) {
return 'plugin/' + rd.plugin + '/index.html';
},
resolve: {
load: function($q, $route, $rootScope) {
var deferred = $q.defer();
var dependencies = [
'plugin/' + $route.current.params.plugin + '/controller.js'
];
$script(dependencies, function () {
$rootScope.$apply(function() {
deferred.resolve();
});
});
return deferred.promise;
}
}
});
Run Code Online (Sandbox Code Playgroud)
controller.js
app.register.controller('MyPluginCtrl', function ($scope) {
...
});
Run Code Online (Sandbox Code Playgroud)
的index.html
<div ng-controller="MyPluginCtrl">
...
</div>
Run Code Online (Sandbox Code Playgroud)