在angular路由中使用正規表示式

積木村の研究所發表於2015-12-14

本文源於對stackoverflow上一道問題的思考:如何在正則angular路由中使用正規表示式中的萬用字元*

在使用angular的過程中,我們經常需要通過不同的url定位到不同的頁面。 這時候我們就可以藉助angular的routeProvider提供的when方法來實現,比如

 myApp.config(['$routeProvider', '$httpProvider',function($routeProvider,$httpProvider) {
     //配置路由
     $routeProvider.
         when('/tab1', {
         templateUrl: 'sections/tab1.html',
         controller: 'Tab1Ctrl',
     }).
         when('/tab2', {
         templateUrl: 'sections/tab2.html',
         controller: 'Tab2Ctrl',
     }).
         when('/tab3', {
         templateUrl: 'sections/tab3.html',
         controller: 'Tab3Ctrl',
     }).
         otherwise({
         redirectTo: '/tab1'
     });

when方法的原型是:when(path, route),其中path

  • path可以包括以冒號開頭的命名組,比如/tab1/:item

  • path可以包含以冒號開頭並以星號結束的命名組,比如/tab1/:item*

  • path可以包含以冒號開頭並以問號結束可選的命名組,比如/tab1/:item?

比如,path為:/color/:color/largecode/:largecode*\/edit會匹配/color/brown/largecode/code/with/slashes/edit 會匹配:

color: brown
largecode: code/with/slashes

但是如果我們要實現以/tab1開頭的url全部路由到/tab1呢?比如/tab1active/tab1touch等都路由到/tab1。用正規表示式描述就是:/tab1.*全部路由到/tab1,使用上述的when方法我們無能為力了。

於是有人出來叫喧說,angular的路由連正規表示式都不支援,實在太弱了,但是其實我們是有方法實現完全按正則進行路由分發地。angular有個$locationChangeStart事件,我們可以監聽這個事件,修改location。下面的例子就可以實現以/tab1開頭的url全部路由到/tab1,即/tab1.*全部路由到/tab1

myApp.config().run(['$rootScope','$location',function($rootScope,$location){
    $rootScope.$on('$locationChangeStart',function(event,next,current){
        var path = /#\/(tab1).*/i.exec(next);
        if(path && path[1]){
            $location.path('/tab1');
        }
    });
}]);

在事件$locationChangeStart觸發時,我們就對路由的變化有了全部的控制,各種正則匹配自然不在話下。

本文同時發表在我的部落格積木村の研究所http://foio.github.io/angular-route/

相關文章