2014-02-16 34 views
12

有沒有什麼方法可以使用角度靜默地更改url欄中的路線?

用戶點擊一個鏈接,就是那張在電子郵件至:

/verificationExecuted?verificationCode=xxxxxx 

頁面加載時我想讀的verificationCode然後將其清除:當我明確

if($location.path() == '/verificationExecuted'){ 
    this.registrationCode = this.$location.search()["verificationCode"]; 
    this.$location.search("verificationCode", null); //Uncomment but make this silent! 

    if(registrationCode != null) { 
     .... 
    } 
    else $location.path("/404");  
} 

會發生什麼它是路線的其餘部分(「/ verificationExecuted」)仍然是路線重新觸發,所以它再次繞過沒有驗證碼並直接到達404。

我想刪除代碼而不做其他任何事情。

回答

23

您可以隨時路線上設置的reloadOnSearch選項是false.

這將防止重裝途徑,如果只查詢字符串發生變化:

$routeProvider.when("/path/to/my/route",{ 
    controller: 'MyController', 
    templateUrl: '/path/to/template.html', 
    //Secret Sauce 
    reloadOnSearch: false 
}); 
0

我對我的一個項目有類似的要求。

我在這種情況下做的是利用服務。

app.factory('queryData', function() { 
    var data; 

    return { 
     get: function() { 
      return data; 
     }, 
     set: function (newData) { 
      data = newData 
     } 
    }; 
}); 

該服務,然後在我的控制器使用:

app.controller('TestCtrl', ['$scope', '$location', 'queryData', 
    function ($scope, $location, queryData) { 
     var queryParam = $location.search()['myParam']; 
     if (queryParam) { 
      //Store it 
      queryData.set(queryParam); 
      //Reload same page without query argument 
      $location.path('/same/path/without/argument'); 
     } else { 
      //Use the service 
      queryParam = queryData.get(); 
      if (queryParam) { 
       //Reset it so that the next cycle works correctly 
       queryData.set(); 
      } 
      else { 
       //404 - nobody seems to have the query 
       $location.path('/404'); 
      } 
     } 
    } 
]);