Passing parameter inside $location.path in Angular

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?


Solution 1:

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

Solution 2:

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;

Solution 3:

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

Solution 4:

  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