How to get the url parameters using AngularJS

How to get the url parameters using AngularJS

HTML source code

$location.url() = {{$location.url()}}
$ = {{$‘keyword’)}}
$location.hash() = {{$location.hash()}}

keyword valus is={{loc}} and ={{loc1}}

AngularJS source code

Here the variables loc and loc1 both return test as the result for the above URL. Is this the correct way?


Solution 1:

I know this is an old question, but it took me some time to sort this out given the sparse Angular documentation. The RouteProvider and routeParams is the way to go. The route wires up the URL to your Controller/View and the routeParams can be passed into the controller.

Check out the Angular seed project. Within the app.js you’ll find an example for the route provider. To use params simply append them like this:

$routeProvider.when('/view1/:param1/:param2', {
    templateUrl: 'partials/partial1.html',    
    controller: 'MyCtrl1'

Then in your controller inject $routeParams:

.controller('MyCtrl1', ['$scope','$routeParams', function($scope, $routeParams) {
  var param1 = $routeParams.param1;
  var param2 = $routeParams.param2;

Solution 2:

While routing is indeed a good solution for application-level URL parsing, you may want to use the more low-level $location service, as injected in your own service or controller:

var paramValue = $; 

This simple syntax will work for However, only if you configured the $locationProvider in the HTML 5 mode before:


Otherwise have a look at the!/path?myParam=someValue “Hashbang” syntax which is a bit more complicated, but have the benefit of working on old browsers (non-HTML 5 compatible) as well.

Related:  Call angularjs function using jquery/javascript

Solution 3:

If you’re using ngRoute, you can inject $routeParams into your controller$routeParams

If you’re using angular-ui-router, you can inject $stateParams

Solution 4:

I found solution how to use $ to get parameter from URL

first in URL u need put syntax ” # ” before parameter like this example


and then in your controller u put $location in function and use $ to get URL parameter for

.controller('yourController', ['$scope', function($scope, $location) {

     var param1 = $; //Get parameter from URL


Solution 5:

If the answers already posted didn’t help, one can try with
with URLs http://example.domain#?myParam=paramValue

Solution 6:

Simple and easist way to get url value

First add # to url (e:g -  test.html#key=value)

url in browser (https://stackover.....king-angularjs-1-5#?brand=stackoverflow)

var url = window.location.href 

(output: url = "https://stackover.....king-angularjs-1-5#?brand=stackoverflow")

output "stackoverflow"