207

HTML source code

<div ng-app="">
    <div ng-controller="test">
      <div ng-address-bar browser="html5"></div>
      <br><br>
      $location.url() = {{$location.url()}}<br>
      $location.search() = {{$location.search('keyword')}}<br>
      $location.hash() = {{$location.hash()}}<br>     
      keyword valus is={{loc}} and ={{loc1}}
  </div>
</div>

AngularJS source code

<script>
function test($scope, $location) {
  $scope.$location = $location;
  $scope.ur = $scope.$location.url('www.html.com/x.html?keyword=test#/x/u');
  $scope.loc1 = $scope.$location.search().keyword ;    
    if($location.url().indexOf('keyword') > -1){    
        $scope.loc= $location.url().split('=')[1];
        $scope.loc = $scope.loc.split("#")[0]        
    }
  }
 </script>

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

Graham
  • 7,431
  • 18
  • 59
  • 84
praveenpds
  • 2,936
  • 5
  • 26
  • 43

9 Answers9

319

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;
  ...
}]);

With this approach you can use params with a url such as: "http://www.example.com/view1/param1/param2"

Jeff
  • 3,549
  • 1
  • 14
  • 11
168

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 = $location.search().myParam; 

This simple syntax will work for http://example.com/path?myParam=paramValue. However, only if you configured the $locationProvider in the HTML 5 mode before:

$locationProvider.html5Mode(true);

Otherwise have a look at the http://example.com/#!/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.

Jérôme Beau
  • 10,608
  • 5
  • 48
  • 52
  • 16
    it seems like you have to add $locationProvider.html5mode(true) as a module config like so: angular.module("myApp", []). config(function($locationProvider) { $locationProvider.html5Mode(true); }); – sq1020 Aug 04 '14 at 16:57
  • 4
    And html5Mode requires a `` tag in your `index.html`. – cespon Mar 31 '15 at 10:33
  • 1
    what I like about your solution is that you can even pass objects, and you get them as object. – Shilan Nov 26 '15 at 12:39
  • 3
    It's also possible to not add the tag and specify it like this: `.config(['$locationProvider', function($locationProvider) { $locationProvider.html5Mode({ enabled: true, requireBase: false }); }])` – Guillaume Nov 11 '16 at 22:42
  • 1
    In Angular 1.5.8, I did not have to configure `$locationProvider` in order for this to work. `http://example.com/path#?someKey=someVal`, then `$location.search().someKey // => 'someVal'` – jiminikiz Mar 31 '17 at 20:33
32

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

http://docs.angularjs.org/api/ngRoute/service/$routeParams

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

https://github.com/angular-ui/ui-router/wiki/URL-Routing

simeg
  • 1,889
  • 2
  • 26
  • 34
jlents
  • 790
  • 8
  • 20
  • 1
    For `$stateParams` to show query parameters, I had to specify them when defining the states, as shown in https://github.com/angular-ui/ui-router/wiki/URL-Routing#query-parameters – Parziphal Jul 22 '14 at 21:14
14

I found solution how to use $location.search() to get parameter from URL

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

"http://www.example.com/page#?key=value"

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

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

     var param1 = $location.search().param1; //Get parameter from URL

}]);
Mekha Lomlao
  • 141
  • 1
  • 3
2

If the answers already posted didn't help, one can try with $location.search().myParam; with URLs http://example.domain#?myParam=paramValue

ak1
  • 104
  • 4
  • 1
    That's the second highest voted solution on here... And posted 3 years before this one... https://stackoverflow.com/a/19481865/3578036 – JustCarty Jan 25 '18 at 11:30
2
function GetURLParameter(parameter) {
        var url;
        var search;
        var parsed;
        var count;
        var loop;
        var searchPhrase;
        url = window.location.href;
        search = url.indexOf("?");
        if (search < 0) {
            return "";
        }
        searchPhrase = parameter + "=";
        parsed = url.substr(search+1).split("&");
        count = parsed.length;
        for(loop=0;loop<count;loop++) {
            if (parsed[loop].substr(0,searchPhrase.length)==searchPhrase) {
                return decodeURI(parsed[loop].substr(searchPhrase.length));
            }
        }
        return "";
    }
Russell Hankins
  • 1,196
  • 9
  • 17
  • window.location.href is actually what I needed in my case. Doesn't always have to be some fancy Angular solution. This didi the trick for me. – Gishas Feb 02 '21 at 12:12
0

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")

url.split('=').pop()
output "stackoverflow"
Rohit Parte
  • 3,365
  • 26
  • 26
0

When using angularjs with express

On my example I was using angularjs with express doing the routing so using $routeParams would mess up with my routing. I used the following code to get what I was expecting:

const getParameters = (temp, path) => {
  const parameters = {};
  const tempParts = temp.split('/');
  const pathParts = path.split('/');
  for (let i = 0; i < tempParts.length; i++) {
    const element = tempParts[i];
    if(element.startsWith(':')) {
      const key = element.substring(1,element.length);
      parameters[key] = pathParts[i];
    }
  }
  return parameters;
};

This receives a URL template and the path of the given location. The I just call it with:

const params = getParameters('/:table/:id/visit/:place_id/on/:interval/something', $location.path()); 

Putting it all together my controller is:

.controller('TestController', ['$scope', function($scope, $window) {
  const getParameters = (temp, path) => {
    const parameters = {};
    const tempParts = temp.split('/');
    const pathParts = path.split('/');
    for (let i = 0; i < tempParts.length; i++) {
      const element = tempParts[i];
      if(element.startsWith(':')) {
        const key = element.substring(1,element.length);
        parameters[key] = pathParts[i];
      }
    }
    return parameters;
  };

const params = getParameters('/:table/:id/visit/:place_id/on/:interval/something', $window.location.pathname);
}]);

The result will be:

{ table: "users", id: "1", place_id: "43", interval: "week" }

Hope this helps someone out there!

Antonio
  • 409
  • 5
  • 12
0

in your router:

url: "/login/reset_password/:user/:token"

in your controller:

let userParam = $state.params.user
let tokenParam = $state.params.token
Anton R
  • 1
  • 3