2012-07-19 90 views
11

這個問題基本上是一個後續問題:AngularJS - How to use $routeParams in generating the templateUrl?。查看我的代碼,瞭解這個問題的正確背景。AngularJS - 基於URL的更新模型

所有的導航部分工作得很好,但現在當我瀏覽時,我想根據primaryNavsecondaryNav更新我的$scope中的一些屬性。我以爲我可以用$watch做點什麼,但我似乎無法得到任何工作。這裏有幾件事情我想:

$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 

我大概可以創造我的控制器一些方法,將採取這些資產淨值和更新的一切,導航關閉,只需添加一個ng-click所有錨標籤。然而,我真正喜歡AngularJS的一件事是爲hrefs使用真正的URL值(例如<a href="#/priNav/secNav">Foo</a>)。當我不通過控制器上的某些方法進行路由時,是否可以根據更改的URL更新我的模型?我希望這是有道理的,我問。

回答

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

你應該通過一個函數或可在範圍

+0

啊......我忘了看函數中進行評估的字符串。我一直在嘗試的是一個字符串。 '$ scope。$ watch($ location.path,function(){});'does not work,but'$ scope。$ watch(function(){return $ location.path()},function(){ ...});'做。謝謝! – dnc253 2012-07-19 23:27:20

+2

謝謝!它甚至適用於[$ location.search](http://sharepointkunskap.wordpress.com/2012/11/22/angularjs-sync-location-search-with-an-input-value/) – 2013-01-28 13:40:39