location是什么?
location是一個關于當前網頁地址的對象,從屬于window之下,當然,window之下的對象在不引起歧義或者混淆的情況下,一般是可以省去window的。location本身是一個js對象,包含一些屬性和方法。具體可以參考w3school 。
angular location
angular中的location是一個service,寫作$location。
getter和setter方法
getter方法用于獲取對象的私有屬性,setter用于設置對象的私有屬性。 js中是不存在私有變量的,但是通過一些命名方式(如私有變量名以雙下劃線開始)約定,可以人為的規定某些變量為私有變量。 正因為js本身不支持私有變量,所以對象的屬性我們都可以通過object.variable的方式讀取。getter和setter方法只是我們為了讓js對象的操作更加規范。例如,可以在setter方法中做一些規則校驗,在getter方法中做一些初始化,等等。
Methods
注:如果方法沒有參數說明或者示例,表示不需要參數。
absUrl()
getter:返回完整url。
hash()
getter:返回hash段。
setter:設置hash段并返回location。如location.hash(‘xxx’)。
host()
getter:返回host。
path()getter:返回路徑。http://a.com/123, path就是123。 setter:設置路徑。$location.path(‘/124’)。
port()
getter:返回端口號。
protocol()
getter:返回協議名,如https。search()
search指的是url的query部分。 window.location.search會返回包括?的部分,個人認為十分不方便解析。 假設url為:http://a.com?name=remind&gender=male, getter: 返回search對象 getter返回對象:{name:’remind’,gender:’male’}。 setter: 設置query,有兩種方式。
1. location.search(′name′,′remind′);location.search(‘gender’,’male’); 這種方法是部分更新(part update)。 如果在一個angular周期中,只更新其中一個,如只執行 $location.search(‘name’,’remind’) 那么gender會自動設置成空,如:http://a.com?name=remind&gender
2. location.search(name:′remind′,gender:′male′);這種方法是全體更新(wholeupdate)。如果在一個angular周期中,執行location.search({name:’remind’}); 那么gender會被刪除,如 : http://a.com?name=remind 可以發現,設置方法類似jQuery設置css的方式,對比一下w3school.遺憾的是search不支持查詢某個特定值,例如location.search(‘name′),返回location對象而不是期待的name值。
Events
當調用$location.path(‘xxx’)使得地址變更時,以下事件會被廣播出去,在angular的作用域(scope)中可以監聽到此類事件。
$locationChangeStart
在$location的path change之后,url change發生改變之前,此事件被廣播出去。url change可以被阻止,方法是調用此事件的preventDefault方法。
$locationChangeSuccess
當url change之后,此event被廣播出去。