Get URL Parameters Using Angular JS

Get URL Parameters Using Angular JS

Get URL parameters in angularjs is very important. Angular JS library have the following methods $loction, $routeParams ,$stateParams which is used to get the URL parameters.

Important Information

-> If you are using ngRoute, you can inject $routeParams into the controller
-> If you are using angular-ui-router, you can inject $stateParams

1. Using $location

It is a very easy way to get the parameter value from the URL. $location.search(); used to get the list of Params in the URL.

Example URL

 neukanndo.com/#/?param1=demovalue1&param1=demovalue2

Source Code

'use strict';
angular.module('myApp')
.controller('MainCtrl', function($scope, $location) {
$outputjson = $location.search();
var param1 = $outputjson.param1; // output demovalue1
var param1 = $outputjson.param2; // output demovalue2
});

2. Using the RouteProvider and routeParams

routeParams only used in ngRoute otherwise it getting there is no RouteProvider.

Example URL

https://www.neukanndo.com/#/homepage/param1/paramval2

Router Example Source

$routeProvider.when('/homepage/:param1/:param2',
{
   templateUrl : 'home/homepage.html',
   controller : 'MyCtrl'
});

Controller Example

'use strict';
angular.module('myApp')
.controller('MyCtrl', ['$scope','$routeParams',function($scope,$routeParams){
var param1 = $routeParams.param1; // output
 var param2 = $routeParams.param2;
}]);

3. Using StateProvider and stateParams

It is used only for angualr-ui-router.

Example URL

https://www.neukanndo.com/#/homepage/paramval2/paramval2​

Router Example Source

$stateProvider
.state('home', {
   url : '/home/:paramid1/:paramid2',
   templateUrl : 'home/homepage.htm1'
});

Controller Example

'use strict';
angular.module('myApp')
.controller('MyCtrl', ['$scope','$stateParams',function($scope,$stateParams){
    var param1 = $stateParams;//output paramval1
    var param2 = $stateParams;//output paramval2
}]);

0 Comments

Leave a Replay

Make sure you enter the(*)required information where indicate.HTML code is not allowed

>