2012-07-19 9 views
11

これは基本的にこの質問の後に続く質問です:AngularJS - How to use $routeParams in generating the templateUrl?。この質問の適切な文脈については私のコードを見てください。AngularJS - URLに基​​づいたモデルの更新

すべてのナビゲーション部分がうまくいきましたが、移動すると$scopeの一部のプロパティをprimaryNavsecondaryNavに基づいて更新したいと考えています。私は$watchで何かできると思ったが、何もできないようだ。私はおそらくこれらのNAVを取り、すべてを更新し、オフに移動し、ちょうどすべてのアンカータグにng-clickを追加することになり、私のコントローラ内のいくつかのメソッドを作成することができます

$scope.$watch($location.path(), function() {...}); //result in js error 
$scope.$watch($location, function() {...}); //function runs once on page load, but not after that 
$scope.$watch($window.location, function() {...}); //function runs once on page load, but not after that 
$scope.$watch(window.location, function() {...}); //function runs once on page load, but not after that 
$scope.$watch(window.location.href, function() {...}); //results in js error 

:ここで私は試したことがいくつかあります。しかし、私がAngularJSについて本当に気に入ったことの1つは、実際のURLを見ている値(例:<a href="#/priNav/secNav">Foo</a>)を使用することでした。コントローラ上の何らかのメソッドを経由せずにルーティングするときに、URLの変更に基づいてモデルを更新することはできませんか?私が求めていることが意味をなさされることを願っています。

答えて

33
$scope.$watch(function() { 
    return $location.path(); 
}, function(){ 
    ... 
}); 

あなたが関数やスコープ

+0

ああの内部で評価することができ、文字列を渡す必要があります...私は、機能を見て忘れてしまいました。私がしようとしていたことはすべて文字列であった。 $ scope. $ watch($ location.path、function(){}); 'は動作しませんが、' $ scope。$ watch(function(){return $ location.path()}、function(){ ...});そうです。ありがとうございました! – dnc253

+2

ありがとう! [$ location.search](http://sharepointkunskap.wordpress.com/2012/11/22/angularjs-sync-location-search-with-an-input-value/)でも機能します。 –

関連する問題