0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【AngularJS】画面ロードさせずにURLのみ変更したい

Posted at

経緯

URL変更時、画面をローディングさせたくないが、ローディング先がapp.jsのルーティング先として登録されているため、ロードされてしまう状態に。

やってみたこと

・$locationによる操作
・window.locationによる操作
・Historyオブジェクトでの操作

ちょっと前に色々試行錯誤したので記憶が曖昧なのですが、試せるだけ試した記憶です。

実装

controller.js
$scope.changeParam = function(){
    // URLパラメータの変更を条件とする
    if ($location.search()["word"] != $scope.word){
       // 元のパスを取得
       var path = $location.path();
       // URL変更の関数を呼び出す
       changeUrl(path);
    }
}

// URL変更時、ロードさせない
var changeUrl = function(path) {
    var lastRoute = $route.current;
    // URL変更時に発火
    var deregistrationFn = $rootScope.$on('$locationChangeSuccess', function () {
	    // URL変更前の情報をURL変更後に代入する
	    $route.current = lastRoute;
	    deregistrationFn();
    });
    $location.url(path);
};

補足

・URL変更前→URL変更後に代入、という形で実現できるようですが、詳しい原理は不明…
・app.jsに登録しているルーティング構成次第では回避できる気がしますが、既に構築済みなルーティング構成をいじる方がしんどい場面などで使えると思います。
・色々調べていたところ、結構特殊な状況らしく、本来なら$locationやHistoryオブジェクトによる履歴の操作などで実装するのがスマートっぽいです。

参考記事

Angularで画面遷移やロードをさせずにURLのみを変更する方法

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?