How to get parameters in the URL through Angularjs

Asked

Viewed 3,456 times

5

Guys I have a URL as follows "test/#/app/product/2" and I wanted to take this number at the end of the URL and use it to make a condition as I do to bring this ID?

  • You’re wearing ngRoute or ui-router to create routes with variables?

  • I use the ui-router

2 answers

3


Assuming that this 2 has been defined as a route variable

.state('produtoView', {
    url: '/produto/:id' ...

You can redeem this variable id by injecting the $stateParams in your controller and taking the value of the route variable by its name $stateParams.id.

Take a look at the documentation of ui-router, below it speaks of a new way of fetching the variable in the new versions of ui-router, then the $stateParams is depreciated.

I didn’t put it the new way because I didn’t know this fact either.

3

Use the service $location.

For example, for a given URL http://example.com/#/some/path?foo=bar&baz=xoxo:

var abUl = $location.absUrl();     // => "http://example.com/#/some/path?foo=bar&baz=xoxo"
var url  = $location.url();        // => "/some/path?foo=bar&baz=xoxo"
var prot = $location.protocol();   // => "http"
var host = $location.host();       // => "example.com"
var path = $location.path();       // => "/some/path"
var srch = $location.search();     // => {foo: 'bar', baz: 'xoxo'}

In your specific case, $Location.path() will return /app/produto/2.

Source.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.