1

I have URL's in project as:

http://blo.c/news http://blo.c/video

How I can get segments news, video from these URL?

I tried to use $location in Angular JS, but this object has not these segments

3 Answers 3

2

You need to use $location.path()

// given url http://blo.c/news
var path = $location.path();
// => "/news"

If you are using HTML5 mode you must ensure $locationProvider.html5Mode(true) is set so $location works properly.

If you are not using HTML5 mode (which is the case here); then you'll need to drop to traditional javascript to get the URL, since you are not using Angular routing in the first place:

// given url http://blo.c/news
var path = window.location.pathname;
// => "/news"

You might choose to inject $window instead of using window directly, this is only a thin wrapper over the native window object but facilitates testing.

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

3 Comments

I get nothing in console.log(path)
Have you got $locationProvider.html5Mode(true);? If you haven't it will still expect a # in the URL. docs.angularjs.org/guide/$location#html5-mode
No I can not use html5 true because my application was build not only on Angular JS, so also work PHP URI
1

Use the $location.path function to get the url. To get what's after the url, use split

$location.path.split(/\{1}/)[1]

1 Comment

TypeError: $location.path.split is not a function. Also what is [1]?
0
const URL = '/seg1/?key=value';
$location.path();// will return URI segment (in above URL it returns /seg1 ).

$location.search(); // getter will fetch URL segment after ? symbol.  
//(in above URL it returns {key:value} object ).

Official Doc: https://docs.angularjs.org/guide/$location

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.