Angularjs Using $location Detailed and sample code _ANGULARJS

Source: Internet
Author: User
Tags angular scope

One, What does it do?

$location Service analyzes the URLs in the browser's address bar (based on window.location), so that we can use the contents of the URL more conveniently in the application. Changing the URL in the Address bar responds to the $location service, and modifying the URL in $location also responds to the address bar.

$location Services:

Exposes the URL of the current browser's address bar, so we can

1. Note and observe the URL
2. Change URL

Sync the URL with the browser when the user does the following:

1. Change the Address bar
2. Click the Back or Forward button (or click a historical link).
3. Click a link

Describes a URL object as a series of methods (Protocol,host,path,search,hash).

1. Compare $location and Window.location

1) Purpose: window.location and $location services allow read-write access to the current browser's location.

2 API:window.location exposes an unprocessed object with some attributes that can be modified directly, while $location service exposes some jquery-style getter/setter methods.

3 The integration with the angular application declaration cycle: $location know about all internal declaration cycle stages, and $watch and other integration; window.location.

4 Seamless integration with the HTML5 API: Yes (with a fallback for legacy browsers, is compatible with a lower version of the browser? ) and window.location not.

5 know the application loaded document root (Docroot) or context: Window.location No, Wnidow.location.path will return "/docroot/subpath", and $location.path ( ) return to the true docroot.

2. When should I use $location?

In applications, any need to respond to changes to the current URL, or to change the URL of the current browser.

3. What does it do?

When the browser URL changes, it does not cause the page to reload (page reload). If you need to do this (change the address, implement page reload), use the lower-level API $window. Location.href.

General overview of the API (overview of APIs)

$location service can behave differently depending on the configuration it initializes. The default configuration is suitable for most applications, and other configuration customizations allow you to turn on some new features.

When the $location service is initialized, we can use it in jquery-style getter and setter methods, allowing us to get or change the URL of the current browser.

1. $location Service Configuration

To configure the $location service, you need to obtain $locationprovider (Http://code.angularjs.org/1.0.2/docs/api/ng. $locationProvider) and set the following parameters:

Html5mode (Mode): {boolean},true-see HTML5 mode;false-see Hashbang mode, default: false. (The following sections explain various mode)

Hashprefix (prefix): {String},hashbang used prefix (Html5mode to false, use Hashbang mode to accommodate browsers that do not support HTML5 mode), default: '! '

2. Getter and Setter methods

The $location service provides getter methods for the read-only URL portion (Absurl,protocol,host,port), and also provides Url,path,search,hash getter and setter methods.

 Get the current path
  $location. path ();

  Change the path
  $location. Path ('/newvalue ')

All setter methods return the same $location object to implement chained syntax. For example, to modify multiple attributes in one sentence, the chain setter method is similar:

$location. Path ('/newvalue '). Search ({key:value});

There is a special replace method that can be used to tell the $location service to use a path to replace the most recent history instead of creating a new one when synchronizing with the browser next time. The Replace method is useful when we want to implement redirection (redirection) without invalidating the Back button (back button to trigger redirection). To change the current URL without creating a new history, we can do this:

$location. Path ('/somenewpath '). replace ();

Note that the setter method does not update window.location immediately. Instead, the $location service knows the scope lifecycle and merges multiple $location changes into one and commits them to the Window.location object in the $digest phase of the scope. Because $location changes in multiple states are merged into a single change, the Replace () method is called only once in the browser, so that the entire commit has only one replace (), which does not cause the browser to create additional history. Once the browser is updated, the $location service resets the flag bit through the Replace () method, and future changes will create a new history unless replace () is called again.

Setter and character encoding

We can pass in special characters to the $location service, and the service will automatically encode them according to the RFC3986 standard. When we access these methods:

    1. The value of all the setter methods passed in $location, path (), search (), hash (), are encoded.
    2. The value returned by the Getter method (without parameters) is decoded, such as Path (), search (), hash ().
    3. When we call the Absurl () method, the value returned is the complete URL that contains the encoded part.
    4. When we call the URL () method, we return the encoded URL that contains the path, search, and hash section, such as/path?search=1&b=c#hash.

Iii. Hashbang and HTML5 Modes

The $location service has two configuration modes that control the URL format of the browser's address bar: Hashbang mode (default) and HTML5 mode based on the use of the HTML5 History API. In both modes, the application uses the same API, $location service works with the right URL fragment, the browser API, and helps us with browser URL changes and history management.

1. Hashbang mode (default mode)

In this mode, the $location uses the Hashbang URL in all browsers. See the following code snippet for more information:

It (' Should show example ', Inject (
  function ($locationProvider) {
    $locationProvider. Html5mode = false;
    $locationProvider. Hashprefix = '! ';
  },
  function ($location) {
  //Open http://host.com/base/index.html#!/ A
  $location. Absurl () = = ' http://host.com/base/index.html#!/a ';
  $location. Path () = = '/a ';
  $location. Path ('/foo ');
  $location. Absurl () = = ' Http://host.com/base/index.html#!/foo ';
  $location. Search () = = {};//search No Dongdong, return empty object
  $location. Search ({A: ' B ', c:true});
  $location. Absurl () = = ' Http://host.com/base/index.html#!/foo?a=b&c ';
  $location. Path ('/new '). Search (' x=y ');//You can change search by string, and each time you set up search, you will overwrite the previous search
  $location. Absurl () = = ' Http://host.com/base/index.html#!/new?x=y ';
  }
));

Crawling your app (allows Google to index our apps)

If we want our AJAX applications to be indexed, we need to add a special meta tag to the head:

<meta name= "Fragment" content= "!"/>

Doing so will allow the crawler to request the current link using the _escaped_fragment_ parameter, let our servers know about the crawler, and provide a corresponding HTML snapshot. To learn more about this technology, you can view the Https://developers.google.com/webmasters/ajax-crawling/docs/specification?hl=zh-CN

Four, HTML5 mode

In HTML5 mode, the getter and setter of the $location service interacts with the browser URL through the HTML5 history API, allowing the use of the normal path, search module, instead of the Hashbang mode. If some browsers do not support the HTML5 History API, $location service automatically returns to the mode using the Hashbang URL. The use of $location services is the right and the best option for us to be freed from the fear of not clearly demonstrating whether our app's browsers support the history API.

Opening a regular URL in an older browser translates to Hashbangurl.

Opening a hashbangurl in a modern browser will be rewritten as a regular URL.

1. Forward compatible with the old version of the browser

For browsers that support the HTML5 history API, $location use them to write path and search. If the browser does not support the history API, $location will be converted to provide Hashbang URLs. This is the $location service automatically converted.

2. HTML Link Rewriting

When we use history API mode, we need different links for different browsers, but we just need to provide regular URLs, such as <a href= "/some?foo=bar" >link</a>

When the user clicks the hyperlink:

In the old browser, the URL is changed to/index.html#!/some?foo=bar

In modern browsers, the URL is changed to/some?foo=bar

In the following scenario, the link is not overridden, but instead causes the page to be loaded into the corresponding URL:

Hyperlink containing target: <a href= "/ext/link?a=b" target= "_self" >link</a>

Absolute links to different domain : <a href= "http://angularjs.org/" >link</a>

After you set the base path, hyperlinks that start with "/" are linked to different base paths: <a href= "/not-my-base/link" >link</a>

3. Server Side

Using this approach, request URL redirection on the server side, usually, we need to redirect all of our links to our applications. (for example, index.html).

4. Crawling your App

Same as before

5. Relative links

Be sure to check all relative links, pictures, scripts, and so on. We must specify the base URL (<base href= "/my-base" >) in

We are very encouraged to run angular applications that allow the use of the history API in document root, since this is a good way to take care of the problem of relative links.

6. Sending links among different browsers

(this explains the two modes of address can be adapted to different browsers, automatic conversion, and repeat once ...) )

7. Examples

In this example, you can see two $location instances, two are HTML5 mode, but in different browsers, so we can see the difference between the two. These $location services are connected to two fake "browsers". Each input represents the browser's address bar.

Notice when we enter the Hashbang address to the first "browser" (or second?). , it does not override or redirect another URL, and this conversion process only occurs when page reload.

<! DOCTYPE html> 

V. Additional Notes

1. Page Reload Navigation

$location Service only allows us to change the URL; it does not allow us to reload the page (reload). When we need to change the URL and reload page or jump to other pages, we need to use the low-level point API, $window. Location.href.

2. Using $location outside of the scope life-cycle

$location know angular's scope life-cycle. When the URL of the browser changes, it updates the $location and calls $apply, so all $watcher and $observer are notified. When we modify the $location in the $digest phase, there is no problem; $location will propagate this change to the browser and notify all $watcher, $observer. When we need to change the $location outside angular (for example, in a DOM event or in a test), we must call $apply to propagate the change.

3. $location. Path () and! Or/prefixes

Path can be started directly with "/", $location. Path () Setter is automatically filled when value does not begin with "/".

Pay attention to "!" Prefixes, in Hashbang mode, are not part of the $location.path (). It's just hashprefix.

VI. Testing with the $location service

When using the $location service in the test, it is outside the angular scope life-cycle. This means that we need to be responsible for calling scope.apply ().

Describe (' Serviceundertest ', function () {
  Beforeeach (function ($provide) {
  $provide. Factory ('  Serviceundertest ', function ($location) {
  //whatever it does ...
  });
  });
  It (' should ... '), inject (function ($location, $rootScope, serviceundertest) {
  $location. Path ('/new/path ');
  $rootScope. $apply ();
  Test whatever the service should do ...});

Vii. migrating from earlier Angularjs releases

In earlier angular, $location used Hashpath or hashsearch to process the path and search methods. In this release, $location service processes the path and search methods when necessary, and then uses the information obtained to form Hashbang URLs (such as Http://server.com/#!/path?search=a).

Eight, two-way binding to $location

Angular compiler does not currently support bidirectional binding (https://github.com/angular/angular.js/issues/404) of methods. If we want to implement bidirectional binding on the $location object (using ngmodel directive in input), we need to specify an additional model property (for example: Locationpath) and add two $watch to listen for $ in two directions. Location updates, for example:

<input type= "text" ng-model= "Locationpath"/>

Js-controller
$scope. $watch (' Locationpath ', function (path) {
  $location. path (path);
);
$scope. $watch (' $location. Path () ', function (path) {
  Scope.locationpath = path;
});

The above is about ANGULARJS Using $location data collation, follow-up continue to supplement the relevant information, thank you for your support of this site!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.