Reference:
- Ng. $location
- Developer guide:angular services:using $location
Brief introduction
$location service resolves the URL in the browser address bar (based on window.location) and makes the URL available in your app. Changing the URL in the Address bar will function to the $location service, and changing the $location service will change the browser's address bar as well. (You can use $location for redirection, etc.)
$location Services:
Exposing the URL in the browser's address bar allows you to:
- Monitor the URL.
- Change the URL.
Synchronize URLs with the browser when:
- Change the Address bar.
- Click Forward, back, or a link in a history.
- Opens a link.
- Represents a URL object as a set of methods. (Protocol, host, port, path, search, hash)
Service dependencies:
- $browser
- $sniffer
- $rootElement
Built-in methods:
- Absurl (): read-only; Returns the URL, with all fragments, according to the rule specified in RFC 3986.
- Hash (): read, write; Returns a hash fragment when it has parameters, and returns $location when the hash fragment is changed in the case of a parameter.
- Host (): read-only; Returns the hosts path in the URL.
- Path (): Read, write, return the path to the current URL when there are no arguments, change the path when the parameter is present, and return $location. (The path returned will always be with/)
- Port (): read-only; Returns the port number of the current path.
- Protocol (): read-only; Returns the protocol for the current URL.
- Replace (): If called, replaces the history in the browser with the changed URL, instead of creating a new message in the history, which prevents "back".
- Search (): reads, writes, and returns the searched part of the current URL as an object when called without arguments.
- URL (): reads, writes, returns a URL when no parameters are returned, and returns $location when the parameter is taken.
Built-in Events:
- $locationChangeStart: Occurs before the URL changes. This change can be prevented by invoking the Preventdefault method of the event. View ng. $rootScope. scope# $on get more details. The $locationchangesuccess event is triggered on success.
- $locationChangeSuccess: Occurs when a URL has changed.
Use when to use $location
Any time you want to change the current URL, you can use $location.
$location won't do it.
When the URL of the browser changes, the entire page is not reloaded. If you want to reload the entire page, you need to use $window.location.href.
"AngularJS" $location service