Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 212
itsme Avatar asked Mar 02 '14 13:03

itsme


2 Answers

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;
};
like image 71
dfsq Avatar answered Nov 06 '22 17:11

dfsq


You can try something like this:

  $routeProvider.when('/asd/:id/:slug', {
    templateUrl: '/views/template.html',
    controller: 'YourController',
    resolve: {
      data: ['$route', 'SecurityFactory',
        function ($route, SecurityFactory) {

          var id= parseInt($route.current.params.id, 10);
          var slug= $route.current.params.slug;

          SecurityFactory.checkParams(id, slug);
        }
      ]
    }
  });

Then inside the SecurityFactory you can check the validity of the params. For example with RegExp.

like image 1
Tome Pejoski Avatar answered Nov 06 '22 17:11

Tome Pejoski