0

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

4 Answers 4

2

You can use $routeParams.id in your controller.

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

2 Comments

This worked. But a bit confused on passing $routeParam. Whether it should be app.controller('productController', [$routeParams,function ($scope, $http) {}]); or app.controller('productController', function ($scope, $http, $routeParams) {});
It's little strange but I use it like this: app.controller('productController', [$routeParams, $scope, $http, function ($routeParams, $scope, $http) { }]); Beware when using it parameters order is important!
2

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

Comments

2

Inject $routeParams to your controller factory function.

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

Comments

1

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

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.