MARKAND Bhatt
MARKAND Bhatt

Reputation: 2650

get Id from the path in angular controller

Following is my $routeProvider.when

.when("/products/:id",{
        templateUrl:"app/views/product.html",
        controller:"productController"
    })

I want to access the value of :id in the product controller.

Based on which i will populate product details.

the url is /index.html#/products/3

Upvotes: 0

Views: 1883

Answers (4)

Ori Drori
Ori Drori

Reputation: 193338

Inject $routeParams to your controller factory function.

.controller('MainController', function($scope, $routeParams) {
     $scope.id= $routeParams.id;
})

Upvotes: 2

Dmitriy Nevzorov
Dmitriy Nevzorov

Reputation: 6078

You can access it in your controller with $routeParams

app.controller('productController', function ($scope, $routeParams) {
  $scope.productId = $routeParams.id;
};

Read more here

$stateParams are for custom ui-router

Upvotes: 2

mihkov
mihkov

Reputation: 1189

You can use $routeParams.id in your controller.

Upvotes: 2

Joe Lloyd
Joe Lloyd

Reputation: 22513

Use the $location service

To access any part of a path you need to use the $location service. It lets you use different parts of the url. For instance (From docs)

// given url http://example.com/#/some/path?foo=bar&baz=xoxo
var url = $location.url();
// => "/some/path?foo=bar&baz=xoxo"

But what you want is this

// given url http://example.com/#/some/path?foo=bar&baz=xoxo
var path = $location.path();
// => "/some/path"

This will return a string that is everything after the #

so then you can Use slice or some other JS function to get the part you need.

Best of luck

Upvotes: 1

Related Questions