Bobby
Bobby

Reputation: 584

How do I parse the location path in AngularJS?

For example the page is 'http://mywebsite/details/555', how can I get that '555' out of there in my controller? It's not a parameter, so I cannot look up for it by name.

Upvotes: 1

Views: 559

Answers (2)

ESP32
ESP32

Reputation: 8718

Your are writing that 555 is not a parameter - but I think you want to use it like a parameter. Parameters look like: http://mywebsite/#/details/555

You can then define this in your router (here I'm using ui-router, but you can do the same with ng-route:

$stateProvider
    .state('details.id', {
        url: "/details/:id",
        templateUrl: 'detail.html',
        controller: myController
    })

See https://github.com/angular-ui/ui-router/wiki/URL-Routing

If you still want to parse your URL string, you can do it this way:

var detailId = this.href.substr(this.href.lastIndexOf('/') + 1);

But the right (and probably the only working) way is to use the router for that.

Upvotes: 1

Bas van Dijk
Bas van Dijk

Reputation: 10713

Have a look at the Angular routing parameters. The number you want is actually and id used in the routing path which you can catch:

Upvotes: 2

Related Questions