Caur
Caur

Reputation: 141

How to get URL segment in Angular JS?

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

Upvotes: 1

Views: 3508

Answers (3)

phpnerd
phpnerd

Reputation: 926

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

Upvotes: 0

seanhodges
seanhodges

Reputation: 17524

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.

Upvotes: 2

Richard Hamilton
Richard Hamilton

Reputation: 26434

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

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

Upvotes: 1

Related Questions