5

我在另一个 SO question 中找到了这个答案。但我也想在某些页面标题中使用路由参数。

如果我有$routeProvider这样的:

$routeProvider.when('/demo/:name/:idNumber', {title : ' - :name', templateUrl: 'partials/details.html', controller: 'AppDetails'}); 

如何:name将标题中的内容:name与位置中的内容相匹配?我尝试了以下

.run(['$location', '$rootScope', '$routeParams', function($location, $rootScope,   $routeParams) {
  $rootScope.$on('$routeChangeSuccess', function (event, current, previous) {
    if(current.$$route.title.contains(":")){
        //Not sure how to get the route param using the title param string
    }else{
      $rootScope.title = current.$$route.title;
    }
  });
}]);

但我不知道如何使用字符串从 routeParams 获取变量。

4

3 回答 3

2

你不能像这样访问它:

$routeParams[$routeParams.title]

我想这就是你要问的,但我不太确定......

于 2014-01-16T16:10:49.233 回答
2

在我添加的 routeChangeSuccess 处理程序中

var title = currentRoute.$$route.title;
if (title && $routeParams){
    for(var paramName in $routeParams) {
        title = title.replace(new RegExp(':' + paramName, 'g'), $routeParams[paramName]);
    }
}
$rootScope.title = title;
于 2014-07-23T19:07:30.317 回答
0

修改你的跑步者以检查这样的标题类型,

    .run(['$rootScope', '$route', '$routeParams', function($rootScope, $route, $routeParams) {
    $rootScope.$on('$routeChangeSuccess', function() {
       if(!!$route.current.title) {
           if(typeof $route.current.title == 'function') {
               document.title = $route.current.title($routeParams);
           } else if (typeof $route.current.title == 'string') {
               document.title = $route.current.title;
           }

       }
    });
}]);

并在 routeProvider 中定义您想要组成标题的函数,例如,

$routeProvider.when('/demo/:name/:idNumber', {
     title : function(params){ return "Name: " + params.name;},
     templateUrl: 'partials/details.html', 
     controller: 'AppDetails'}); 
于 2015-11-23T12:14:00.843 回答