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 ?
import ActivatedRoute from '@angular/router'. Inject ActivatedRoute class in constructor. Access queryParams property of ActivatedRoute class which returns an observable of the query parameters that are available in the current URL route.
path([path]); This method is getter / setter. Return path of current URL when called without any parameter.
The $location is very useful service in AngularJS to read or change the URL in the browser. It use "window. location" in base and make URL available to our application.
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:
// You need to add 'ngRoute' as a dependency in your app angular.module('ngApp', ['ngRoute']) .config(function ($routeProvider, $locationProvider) { // configure the routing rules here $routeProvider.when('/backend/:type/:id', { controller: 'PagesCtrl' }); // enable HTML5mode to disable hashbang urls $locationProvider.html5Mode(true); }) .controller('PagesCtrl', function ($routeParams) { console.log($routeParams.id, $routeParams.type); });
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With