Passing parameter inside $location.path in Angular

JavascriptAngularjs

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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 - Javascript

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 - Javascript

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 - Javascript

  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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionaaduView Question on Stackoverflow
Solution 1 - Javascriptmohsen dorparastiView Answer on Stackoverflow
Solution 2 - Javascriptkrzysiek.steView Answer on Stackoverflow
Solution 3 - JavascriptLucas PiresView Answer on Stackoverflow
Solution 4 - JavascriptFilipeGView Answer on Stackoverflow