4

初めての AngularJS アプリを作成しています。

ルートの変更時にページのタイトルを動的に変更したいので、最初にアプリを次のように構成しようとしました。

<html ng-app>

ページレベルのコントローラーが必要で、その下にサブコントローラーが必要です。

だから、私は次のことから始めました:

var app = angular.module("squareUpYourSavings", ["page1", "page2", "..."]);

app.controller('GlobalController', ['$scope', '$rootScope', function GlobalController($scope, $rootScope) {

    $rootScope.$on('$routeChangeSuccess', function (event, current, previous) {
        $rootScope.title = current.$$route.title;
    });

    $rootScope.$on("$locationChangeStart", function (event, nextLocation, currentLocation) {
            console.log('nextLocation :: ' + nextLocation);
            console.log('currentLocation :: ' + currentLocation);
        });

しかし、これはうまくいきません。(理由はわかりません)ディレクトリレベルのコントローラーを指すナビゲーションがあり、ng-view DOESは機能しますが、 <title> は変わりません。$locationChange リスナーもまったく起動しません。この最上位のコントローラーはまったく聞こえていないかのようです。

そこで、 <html> 要素を変更して最上位のコントローラーを指定しました。

<html id="ng-app" ng-controller="GlobalController">

これは機能するようになりましたが、ルートが 2 回発火しているようです。最初のページ読み込みはこれを示しています:

nextLocation :: location.html#/
currentLocation :: location.html#/ 

その後、ルートに移動すると、前後に正しく起動しますが、そこに到達すると二重に起動します:

nextLocation :: location.html#savings-video         // expected
currentLocation :: location.html#/                  // expected
nextLocation :: location.html#/savings-video/       // not expected
currentLocation :: location.html#savings-video      // not expected

これは予想される動作ですか?私は何を間違っていますか?

ありがとう、スコット

4

1 に答える 1

0

タイトルのように、特定のモジュールではなくアプリ全体に関連するグローバルなものについては、ロジックをメインコントローラーに配置することをお勧めします:モジュールメソッドrun:

var app = angular.module("squareUpYourSavings", ["page1", "page2", "..."]);
app.run(function($rootScope) {
     $rootScope.$on('$routeChangeSuccess', function (event, current, previous) {
         $rootScope.title = current.$$route.title;
     });
});

ああ、ルーターを離れて、どのコントローラーが「制御」 されているかを判断する必要があります。

<html ng-app> 
于 2013-11-07T15:01:30.000 に答える