基于路由的AngularJS动态加载控制器和模板
我试图根据路径动态加载模板和控制器(在Angular 1.6中),从当前目录体系结构中拉出。
app
|__login.module.js
|__home.controller.js
|__login.factory.js
|__home.view.html
|__404.view.html
|__index.html
目前,下面的代码工程来拉适当的模板,但控制器不会加载:
angular.module('common.auto-loading-routes', []).config(function($routeProvider){
function getTemplate(routeParams){
var route = (routeParams.current) ? routeParams.current.params.route : routeParams.route;
var directory = route.split('/');
directory = directory.filter(function(entry) { return entry.trim() != ''; });
var page = directory[directory.length - 1];
directory.splice(-1,1);
directory = directory.join('/');
return directory + '/' + page +'.view.html';
}
function getController(routeParams){
//I think I need a promise here, but I don't know how to write it
routeParams = routeParams.route.split('/').join('.');
return routeParams + 'controller';
}
$routeProvider.when('/:route*', {
controller: function($routeParams) { //does not work
return getController($routeParams);
},
templateUrl: function($routeParams) { //works
return getTemplate($routeParams);
},
resolve: {
check: function($route, $http, $location){
return $http.get(getTemplate($route)).then(function(response){
if (response.status !== 404){
return true;
} else {
$location.path('404');
}
});
}
}
}).otherwise('/404');
});
我明白控制器需要在应用程序开始时出现,但我无法用promise声明书写正确的resolve 。
有人可以帮我解决一个简单的承诺,根据路线返回一个控制器名称的字符串?
我能够通过在路由中不包括控制器来实现它的工作。 相反,我把ng-controller属性放在我加载的视图中。
这工作!
angular.module('common.auto-loading-routes', []).config(function($routeProvider){
function getTemplate(routeParams){
var route = (routeParams.current) ? routeParams.current.params.route : routeParams.route;
var directory = route.split('/');
directory = directory.filter(function(entry) { return entry.trim() != ''; });
var page = directory[directory.length - 1];
directory.splice(-1,1);
directory = directory.join('/');
return directory + '/' + page +'.view.html';
}
$routeProvider.when('/:route*', {
templateUrl: function($routeParams) { //works
return getTemplate($routeParams);
},
resolve: {
check: function($route, $http, $location){
return $http.get(getTemplate($route)).then(function(response){
if (response.status !== 404){
return true;
} else {
$location.path('404');
}
});
}
}
}).otherwise('/404');
});
在这个观点的HTML中,我只是说
ng-controller="home.controller"(或者其他合适的控制器) 链接地址: http://www.djcxy.com/p/77613.html
上一篇: AngularJS Dynamically Load Controller and Template based on Route
