I want to extract data from current URL and use it in controller. For example I have this url:
app.dev/backend/surveys/2
Bits that I want to extract:
app.dev/backend/ :type / :id
Is there anything in Angular that could help me with this task ?
I want to extract data from current URL and use it in controller. For example I have this url:
app.dev/backend/surveys/2
Bits that I want to extract:
app.dev/backend/ :type / :id
Is there anything in Angular that could help me with this task ?
Just inject the routeParams service:
http://docs.angularjs.org/api/ngRoute.$routeParams
To get parameters from URL with
ngRoute
. It means that you will need to include angular-route.js in your application as a dependency. More information how to do this on official ngRoute documentation.The solution for the question:
If you don't enable the
$locationProvider.html5Mode(true);
. Urls will use hashbang(/#/
).More information about routing can be found on official angular $route API documentation.
Side note: This question is answering how to achieve this using ng-Route however I would recommend using the ui-Router for routing. It is more flexible, offers more functionality, the documentations is great and it is considered the best routing library for angular.
In your route configuration you typically define a route like,
You can then either get the route in the resolve object by using
$route.current.params
or in a controller,$routeParams
. In either case the parameters is extracted using the mapping of the route, soparam1
can be accessed by$routeParams.param1
in the controller.Edit: Also note that the mapping has to be exact
Will only match a single parameter.
Will only match two parameters.
This is a bit different then most dynamic server side routes. For example NodeJS (Express) route mapping where you can supply only a single route with X number of parameters.
You could inject
$routeParams
to your controller and access all the params that where used when the route was resolved.E.g.:
See angular $routeParams documentation for further information.
Better would have been generate url like
and then use
and inject $location in controller.
ex: url/:id