Angular 1 - get current URL parameters

前端 未结 6 1223
情话喂你
情话喂你 2020-11-30 03:37

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 t

6条回答
  •  一整个雨季
    2020-11-30 04:24

    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.

提交回复
热议问题