如何在位置变化时获取路线名称?

Fre*_*ind 28 angularjs

我定义了一些路线:

angular.module('myApp', [])
  .config('$routeProvider', function($routeProvider) {
    $routeProvider.when('/aaa', { templateUrl: '/111.html' })
                  .when('/bbb', { templateUrl: '/222.html'});
  });
Run Code Online (Sandbox Code Playgroud)

我想在用户更改路线时获取路线名称:

angular.module('myApp')
  .run(['$rootScope', function($rootScope) {
    $rootScope.$on('$routeChangeSuccess', function(scope, current, pre) {
      // how to get current route name, e.g. /aaa or /bbb
      console.log('Current route name: ' + ???);
    }
  }]);
Run Code Online (Sandbox Code Playgroud)

但我不知道如何得到它.我可以得到templateUrl,但不是路线名称.


UPDATE

一个更复杂的用例:

$routeProvider.when('/users/:id', { templateUrl: '/show_user.html' })
Run Code Online (Sandbox Code Playgroud)

如果当前路径是:

/users/12345
Run Code Online (Sandbox Code Playgroud)

它应匹配/users/:id,但我如何知道哪条路线匹配并获得路线名称/users/:id

F L*_*has 62

您可以注入$ location服务并使用其path()函数.

angular.module('myApp')
  .run(['$rootScope','$location', '$routeParams', function($rootScope, $location, $routeParams) {
    $rootScope.$on('$routeChangeSuccess', function(e, current, pre) {
      console.log('Current route name: ' + $location.path());
      // Get all URL parameter
      console.log($routeParams);
    });
  }]);
Run Code Online (Sandbox Code Playgroud)

您可以在文档中找到其他有用的$ location方法

UPDATE

如果你想拥有一个当前路由参数的数组,只需像上面那样注入$ routeParams服务.

  • 仅供参考:Angular中偶数处理程序的第一个参数不是范围,它是一个事件.我已编辑了您的代码段以反映这一点.FWIW,`currentScope`在事件对象上可用. (2认同)

Ale*_*aev 8

你不必注射$location$routeParams.
您可以使用current.$$route.originalPath

app.run(function ($rootScope) {
    $rootScope.$on('$routeChangeSuccess', function (e, current, pre) {
        console.log(current.$$route.originalPath);
    });
});
Run Code Online (Sandbox Code Playgroud)

这对于简单的路线(没有:id等)就足够了.

随着更复杂的用例,它将返回/users/:id.
但是您可以:idcurrent.params.id完整路径中提取并替换它.

app.run(function ($rootScope) {
    $rootScope.$on('$routeChangeSuccess', function (e, current, pre) {
        var fullRoute = current.$$route.originalPath,
            routeParams = current.params,
            resolvedRoute;

        console.log(fullRoute);
        console.log(routeParams);

        resolvedRoute = fullRoute.replace(/:id/, routeParams.id);
        console.log(resolvedRoute);
    });
});
Run Code Online (Sandbox Code Playgroud)

根据您对路线字符串的确切要求,与Flek的答案相比,这可能是混乱的(例如,如果您有多个参数),或者您不希望被绑定到路线参数名称.

另请注意:您的代码中有一个缺少右括号的$on开括号.

编辑15/01/2014

看起来$$Angular中的属性是私有的,我们不应该直接从我们的代码中调用它们.