Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
2
rated 0 times [  5] [ 3]  / answers: 1 / hits: 129433  / 11 Years ago, wed, december 18, 2013, 12:00:00

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 ?


More From » angularjs

 Answers
13

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.


[#73679] Tuesday, December 17, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
katelinb

Total Points: 535
Total Questions: 104
Total Answers: 109

Location: Burkina Faso
Member since Sun, Jun 13, 2021
3 Years ago
;