18

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.

3 Answers 3

33

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.

Sign up to request clarification or add additional context in comments.

1 Comment

In this scenario, is the only advantage to using $location dependency injection? (Seems like NG should provide some convenient API...)
13

If you'd like to get the last piece of the string, you may do something like this

function MainController($location){
   var pId = $location.path().split(/[\s/]+/).pop();
     console.log(pId);         //321
}

Comments

1

In case somebody else lands here seeking help related to retrieving the url in Angular. Occasionally, one might need to access the absUrl:

console.log($location.absUrl());
http://127.0.0.1:3000/home

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.