Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get part of url in AngularJS

URL may be

person/show/31586

or

person/show/31586#tab1

Is it possible to get the ID in angular way? The routing is not managed by angular. The above url loads a page and just some content on the page is managed by angular.

like image 900
UpCat Avatar asked Aug 07 '13 07:08

UpCat


People also ask

How to get current URL AngularJS?

We will be using the $location. absURL() method to get the complete URL of the current page. Example 1: Just use the $location. absURL() method to get the complete URL of the current page.

How to change URL path in AngularJS?

To change path URL with AngularJS, $location. path() is passed the new URL as a parameter, and the page is automatically reloaded. This means that if you ever make a change to the URL in an Angular application, then the partial and controller will be reloaded automatically.

What is HTML5mode?

In HTML5 mode, the $location service getters and setters interact with the browser URL address through the HTML5 history API. This allows for use of regular URL path and search segments, instead of their hashbang equivalents.

What is $location in AngularJS?

Overview. The $location service parses the URL in the browser address bar (based on the window. location) and makes the URL available to your application. Changes to the URL in the address bar are reflected into $location service and changes to $location are reflected into the browser address bar.


1 Answers

The $location service parses the URL from the browser address bar and makes the URL available to your app. Because you're using regular URL path and search segments, you have to set html5Mode to true with $locationProvider.

By default, $locationProvider uses hashbangs, so if you don't set html5Mode to true, you will get an empty string when you try to fetch the URL path.

After you set html5mode, you can use the $location service to fetch the URL path, and write your own rule to process the path.

For example, assume that your full URL looks like: http://example.com/person/show/321

Then in main.js you might have:

angular.module("MyAPP",[],function($locationProvider){
    $locationProvider.html5Mode(true);
});

function MainController($location){
    var pId = $location.path().split("/")[3]||"Unknown";    //path will be /person/show/321/, and array looks like: ["","person","show","321",""]
    console.log(pId);
}

And in index.html you might have:

<!DOCTYPE html>
<html lang="en" ng-app="MyAPP">
    <head>
        <meta charset="utf-8">
        <title>Angular test</title>
    </head>
    <body ng-controller="MainController">
        <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
        <script src="js/main.js"></script>
    </body>
</html>

Hope this is helpful for you.

like image 133
Chickenrice Avatar answered Sep 22 '22 14:09

Chickenrice