可以根据路由组动态加载控制器,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' */ } });
我看到很多这样的问题,但没有一个加载基于路由组的js文件/控制器.
我设法解决了由@calebboyd,http://ify.io/lazy-loading-in-angularjs/和
http://weblogs.asp.net/dwahlin/archive/2013/05/22/dynamically-loading-controllers-and-views-with-angularjs-and-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 }; });
然后我注册“按组控制器”路由.
$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; } } });
controller.js
app.register.controller('MyPluginCtrl',function ($scope) { ... });
的index.html
<div ng-controller="MyPluginCtrl"> ... </div>