Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 1 - get current URL parameters

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 ?

like image 412
sarunast Avatar asked Dec 18 '13 10:12

sarunast


People also ask

How to get URL query params Angular?

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.

Which method of $location service is used to get the current URL without any parameters?

path([path]); This method is getter / setter. Return path of current URL when called without any parameter.

What is $location in AngularJS?

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.


1 Answers

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.

like image 86
sarunast Avatar answered Sep 21 '22 22:09

sarunast