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

后端 未结 3 406
一生所求
一生所求 2020-12-15 08:11

i\'m simply doing setting this:

app.config([\'$routeProvider\',function($routeProvider) {
  $routeProvider
  .when(\'/asd/:id/:slug\',{
    templateUrl:\'vie         


        
相关标签:
3条回答
  • 2020-12-15 08:32

    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;
    };
    
    0 讨论(0)
  • 2020-12-15 08:33

    Not a very elegant solution, and I have only tested it in Chrome DevTools, but it seems to work:

    Object.getPrototypeOf($route.current) === $route.routes['/asd/:id/:slug'];
    

    It seems that the routes property of the $routes service is an object literal with the keys set to the patterns for each route.

    For others wanting to use this, just replace '/asd/:id/:slug' with the pattern that you used when you defined your route.

    Also if you want to match the otherwise path, just use $route.routes['null']

    Disclaimer: This is just a workaround that I found and which works for me. Given that this behavior is not documented, and that I didn't test it to see if it works in all scenarios, use it at your own risk.

    0 讨论(0)
  • 2020-12-15 08:44

    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.

    0 讨论(0)
提交回复
热议问题