14

我只是在做这样的设置:

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

:id 和 :slug 是动态参数。

现在我想走check if current url matches那条路线(/asd/:id/:slug

例如网址:asd/5/it-is-a-slug

哪个是最简单的方法?

我试过这个:

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

但有时它在切换页面路由时不会在控制台中返回任何内容

4

3 回答 3

25

当前路由允许您使用正则表达式。注入$route服务并探索当前路由对象。即regexp部分:

$route.current.regexp

这是您可以使用它的方式(来自控制器方法的示例,以检查是否应激活当前菜单项(具有动态部分)):

$scope.isActive = function (path) {
    if ($route.current && $route.current.regexp) {
        return $route.current.regexp.test(path);
    }
    return false;
};
于 2014-03-02T14:27:24.710 回答
1

你可以尝试这样的事情:

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

然后在SecurityFactory中,您可以检查参数的有效性。例如使用RegExp

于 2014-03-02T13:57:54.457 回答
0

不是一个非常优雅的解决方案,我只在 Chrome DevTools 中对其进行了测试,但它似乎有效:

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

似乎 $routes 服务的 routes 属性是一个对象文字,其键设置为每个路由的模式。

对于其他想要使用它的人,只需替换'/asd/:id/:slug'为您在定义路线时使用的模式。

另外,如果您想匹配otherwise路径,只需使用$route.routes['null']

免责声明:这只是我发现的一种解决方法,对我有用。鉴于此行为未记录在案,并且我没有对其进行测试以查看它是否适用于所有场景,因此使用它需要您自担风险。

于 2015-07-29T17:40:26.247 回答