Angular js - check if current url matches the route (with dynamic url params)

itsme picture itsme · Mar 2, 2014 · Viewed 25.6k times · Source

i'm simply doing setting this:

app.config(['$routeProvider',function($routeProvider) {
  $routeProvider
  .when('/asd/:id/:slug',{
    templateUrl:'views/home/index.html',
    controller:'Home',
    publicAccess:true,
    sessionAccess:true
  });

:id and :slug are dynamic params.

Now i would like to check if current url matches that route (/asd/:id/:slug)

for example the url : asd/5/it-is-a-slug

which is the simplest way?

i tryed this :

$rootScope.$on('$routeChangeStart', function(){ 
   console.log($route.current); 
});

but sometimes it returns nothing in console while switching page routes

Answer

dfsq picture dfsq · Mar 2, 2014

Current route allows you to use regular expression. Inject $route service and explore current route object. Namely regexp part:

$route.current.regexp

This is how you can use it (example from controller method to check if current menu item (which has dynamic parts) should be activated):

$scope.isActive = function (path) {
    if ($route.current && $route.current.regexp) {
        return $route.current.regexp.test(path);
    }
    return false;
};