Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
626 views
in Technique[技术] by (71.8m points)

angularjs - How to get the route name when location changes?

I defined some routes:

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

And I want to get the route name when user changes the route:

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: ' + ???);
    }
  }]);

But I don't know how to get it. I can get the templateUrl, but not the route name.


UPDATE

A more complex use case:

$routeProvider.when('/users/:id', { templateUrl: '/show_user.html' })

If current path is:

/users/12345

It should match /users/:id, but how do I know which route is matched and to get the route name /users/:id?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can inject the $location service and make use of its path() function.

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);
    });
  }]);

You can find other useful $location methods in the docs

UPDATE

If you want to have an array of your current route parameters, just inject the $routeParams service like I did above.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...