javascript - AngularJS 动态路由

标签 javascript angularjs content-management-system url-routing

我目前有一个内置路由的 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/

相关文章:

javascript - 领英 API : Dynamic UI Component

javascript - 如何在单击事件发生的确切位置获得弹出的工具提示?

javascript - 当 DOM 对象已在 Angular 中渲染时,如何调用 Controller 中指定的函数?

开放式数据和数据类型的数据库结构和关联

如果对象存在,则调用方法的 Javascript 速记

javascript - 如何使石头剪刀布只能选择有效选项

javascript - 两个日期之间的虚线 amcharts

javascript - 过滤 ng-repeat 以从对象属性创建逗号分隔的数组值列表

php - 带 pdo 和 mysql 的动态多级 Bootstrap 菜单

jQuery 未捕获类型错误 : Property '$' of Object is not a Function