87

I'm just trying to use $location.path() in my controller but also passing a custom variable as a parameter. So it would look something like this I guess:

$scope.parameter = 'Foo';

$location.path('/myURL/' + $scope.parameter);

But that doesn't work. Anyone know how this is supposed to be done in Angular?

180

to add Parameters you should use $location.search() method so:

$location.path('/myURL/').search({param: 'value'});

$location methods are chainable.

this produce :

/myURL/?param=value
|improve this answer|||||
  • check spelling, Upper/Lower case and its bindings – mohsen dorparasti Mar 27 '14 at 13:33
  • Is there any way to convert this so the url looks like /myUrl/value instead of /myURL/?param=value ? – AzzyDude Mar 27 '14 at 13:35
  • 1
    you can use .Path('/myURL/' + value).but then it's not called parameter anymore . – mohsen dorparasti Mar 27 '14 at 13:36
  • 2
    I had to remove the trailing / to get this to work. This code is the working copy $location.path('/myURL').search({param: 'value'}); – bodagetta Dec 2 '14 at 20:23
38

The another way to add parameter to url is:

 $location.path('/myURL/'+ param1);

and you can define route to myPage.html:

config(['$routeProvider', function ($routeProvider) {
        $routeProvider.when('/myURL/:param1', {
            templateUrl: 'path/myPage.html',
            controller: newController
            });
    }]);

The parameter can then be accessed in newController as follows:

var param1= $routeParams.param1;
|improve this answer|||||
  • 1
    Is that answer adding a query parameter or a route attribute? – Phil Aug 1 '16 at 12:36
12

For example if you need to put in your URL one or more parameters:

$location.path('/path').search({foo: 'valueFoo', baz:'valueBaz'})

in your url will represent

/path?foo=valueFoo&baz=valueBaz

To get params in an other controller:

var urlParams = $location.search();


urlParams.foo will return valueFoo

urlParams.baz will return valueBaz
|improve this answer|||||
2
  function pathToSomewhere() {
    $stateParams.name= vm.name; //john
    $stateParams.phone= vm.phone; //1234
    $stateParams.dateOfBirth= getDoB(); //10-10-1990

    $location.path("/somewhere/").search($stateParams);

  };

This results in the url

http://middle-of-nowhere.com/#/somewhere/?name=john&phone=1234&dateOfBirth=10-10-1990

This way you don't have to manually type out the parameters inside brackets

|improve this answer|||||
  • I'm assuming you have $stateParams injected on your controller for this to work. – FilipeG May 25 '17 at 0:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.