我目前有一个内置路由的 AngularJS 应用程序。 它工作正常,一切正常。
我的 app.js 文件如下所示:
angular.module('myapp', ['myapp.filters', 'myapp.services', 'myapp.directives']).
config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/', { templateUrl: '/pages/home.html', controller: HomeController });
$routeProvider.when('/about', { templateUrl: '/pages/about.html', controller: AboutController });
$routeProvider.when('/privacy', { templateUrl: '/pages/privacy.html', controller: AboutController });
$routeProvider.when('/terms', { templateUrl: '/pages/terms.html', controller: AboutController });
$routeProvider.otherwise({ redirectTo: '/' });
}]);
我的应用内置了 CMS,您可以在其中复制和添加新的 html 文件到 /pages 目录。
即使对于新的动态添加的文件,我仍然希望通过路由提供程序。
在理想的世界中,路由模式应该是:
$routeProvider.when('/pagename', { templateUrl: '/pages/pagename.html', controller: CMSController });
因此,如果我的新页面名称是“contact.html”,我希望 Angular 选择“/contact”并重定向到“/pages/contact.html”。
这可能吗?!如果是的话怎么办?!
更新
我现在在我的路由配置中有这个:
$routeProvider.when('/page/:name', { templateUrl: '/pages/home.html', controller: CMSController })
在我的 CMSController 中:
function CMSController($scope, $route, $routeParams) {
$route.current.templateUrl = '/pages/' + $routeParams.name + ".html";
alert($route.current.templateUrl);
}
CMSController.$inject = ['$scope', '$route', '$routeParams'];
这会将当前的 templateUrl 设置为正确的值。
但是我现在想用新的 templateUrl 值更改 ng-view。这是如何实现的?
最佳答案
angular.module('myapp', ['myapp.filters', 'myapp.services', 'myapp.directives']).
config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/page/:name*', {
templateUrl: function(urlattr){
return '/pages/' + urlattr.name + '.html';
},
controller: 'CMSController'
});
}
]);
- 添加 * 让您可以动态地处理多级目录。 示例:/page/cars/selling/list 将在此 vendor 处捕获
来自文档 (1.3.0):
"If templateUrl is a function, it will be called with the following parameters:
{Array.} - route parameters extracted from the current $location.path() by applying the current route"
还有
when(path, route) : Method
- path can contain named groups starting with a colon and ending with a star: e.g.:name*. All characters are eagerly stored in $routeParams under the given name when the route matches.
关于javascript - AngularJS 动态路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13681116/