cscan
cscan

Reputation: 3840

Angular $routeParams empty object

I'm trying to get a query value from my url using angular's routeParams.

I've included angular-route in my html page:

 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular-route.min.js"></script>

Included Ng-Route in my app:

var app = angular.module('app', [
    'ngRoute',
    'reportController'
]);

And set up my controller as following:

var reportController = angular.module('reportController', []);
reportController.controller('CandidateCtrl', ['$scope', '$routeParams',
        function($scope, $routeParams) {
    console.log(JSON.stringify($routeParams, null, 4));
    $scope.person = $routeParams.person;
}]);

When I access the following URL, however, routeParams is an empty object: {}.

http://localhost:8080/report?person=afe75cc7-fa61-41b3-871d-119691cbe5ad

What am I doing wrong?

Edit:

I've configure the possible route - my routeParams object is still coming up null. I've tried:

famaApp.config(['$routeProvider', function($routeProvider) {
           $routeProvider.
            when('/report:person', {templateUrl: 'Report.html', controller: 'CandidateCtrl'});
}]);

and

when('/report?person', {templateUrl: 'Report.html', controller: 'CandidateCtrl'});

Upvotes: 1

Views: 1364

Answers (2)

maddygoround
maddygoround

Reputation: 2280

Rather then accessing like http://localhost:8080/report?person=afe75cc7-fa61-41b3-871d-119691cbe5ad

try to access it like http://localhost:8080/#/report/afe75cc7-fa61-41b3-871d-119691cbe5ad

you will get the guid in $route.Params

Upvotes: 1

Frederico Jesus
Frederico Jesus

Reputation: 668

You have to set your routes to receive the arguments you want with $routeProvider..

Example:

app.config(['$routeProvider', '$locationProvider' function ($routeProvider, $locationProvider) {

    $routeProvider
        .when('/',
        {
            templateUrl: 'someHtmlUrl',
            controller: 'someController',
            controllerAs: 'someCtrl',
            caseInsensitiveMatch: true
        })
        .when('/:person',
        {
            templateUrl: 'someHtmlUrl',
            controller: 'someController',
            controllerAs: 'someCtrl',
            caseInsensitiveMatch: true
        })
        .otherwise(
        {
            templateUrl: 'someHtmlUrl'
        });
    $locationProvider.html5Mode(true); //Use html5Mode so your angular routes don't have #/route
}]);

Then you can just do

http://localhost:8080/afe75cc7-fa61-41b3-871d-119691cbe5a

And the $routeProvider will call your html and your controller as you can see with the .when('/:person'.. and then you can try and access your $routeParams and you will have your person there, $routeParams.person.

Upvotes: 0

Related Questions