2013-02-19 69 views
5

我需要觀察URL欄上的更改,並根據該更改執行某些操作。我想知道添加手錶以查看更改的最佳方式是什麼?

回答

12

活動存在,他們只是沒有證件的某些原因。

請嘗試以下事件:$locationChangeStart$locationChangeSuccess

scope.$on('$locationChangeStart', function (event, newLoc, oldLoc){ 
    console.log('changing to: ' + newLoc); 
}); 

scope.$on('$locationChangeSuccess', function (event, newLoc, oldLoc){ 
    console.log('changed to: ' + newLoc); 
}); 

或者你也可以$通過傳遞函數爲$手錶的第一個參數看你想要的任何值安德斯建議:

scope.$watch(function() { return $location.path(); }, function(newLoc, oldLoc){ 
    console.log(newLoc, oldLoc); 
}); 

然而這會在您的$摘要中創建更多的開銷。

+0

Thanks @blesh。試圖確定這兩個事件何時發出,以及它們之間的區別是什麼。有任何想法嗎? – Lior 2013-02-19 21:18:59

+0

它的所有設置都在$ location的初始化代碼中。 [看看GitHub上的源代碼](https://github.com/angular/angular.js/blob/master/src/ng/location.js)。只需CTRL + F $ locationChangeStart。它與$ watch()方法建議的基本相同,但它已經爲您設置,所以開銷較少。 – 2013-02-19 21:55:50

+0

簡而言之,'$ locationChangeStart'首先發生,併爲您提供一個選項,以防止傳遞給它的事件對象上的preventDefault()變更。位置成功更改後,$ locationChangeSuccess觸發。 (而是,當你承諾改變位置)。 – 2013-02-19 21:57:26

1

假設您所請求的$位置對象在你的控制器,你可以做這樣的:

$scope.$watch(function() { return $location.path() }, function() { 
    // Do stuff when the location changes 
});