naiveTechie naiveTechie - 4 months ago 48
AngularJS Question

angularjs pass query parameter

Right now i am calling below code :

http://localhost:8081/cgi/#/home


And it takes me to my home page.

My app.js is :

angular.module('myModule',
['ngRoute', 'ngCookies', 'ui.bootstrap',
'angularUtils.directives.dirPagination'])
.config([ '$routeProvider', function($routeProvider) {

$routeProvider.when('/index', {
controller : 'homeController',
templateUrl : './app/views/index.html',
})

.when('/', {
controller : 'homeController',
templateUrl : './app/views/home.html'
})

.otherwise({
redirectTo : '/'
});
}])


Now I need to add extra parameter "debug", which I can store in my controller and if it is there I need to call some function.

I have tried adding below to my app.js

.when('/debug', {
controller : 'homeController',
templateUrl : './app/views/home.html',
})


and below line to my controller

$scope.debug = $routeParams.debug === 'true' ? true : false;
console.log($scope.debug);


in my controller :

var app = angular.module('myModule');
app.controller('homeController', function($scope, $http, $route) {
$scope.debug = $routeParams.debug === 'true' ? true : false;
console.log($scope.debug);
}


Also please include url you think would work in answer as I can unserstand from where to start looking for either routeProvider or $location functionality

But page has now stopped loading and I don't have any clue how can I make it work.
Please help

Answer

You need to inject the $routeParams service to the controller. Just add it as a parameter to the controller function.

var app = angular.module('myModule');
app.controller('homeController', function($scope, $http, $route, $routeParams) {
    $scope.debug = $routeParams.debug === 'true' ? true : false;
    console.log($scope.debug);
}

--- Update ---

Use $location.path() === '/debug' to check if the current path is '/debug'. You need to inject the $location service.

var app = angular.module('myModule');
app.controller('homeController', function($scope, $http, $route, $location) {
    $scope.debug = $location.path() === '/debug';
    console.log($scope.debug);
}
Comments