Stéphane de Luca
Stéphane de Luca

Reputation: 13563

Angularjs: how to handle parameter in url with routing

My URL scheme is as follows:

/drive/Fertilisation?open=potasse

I get to a page as follows:

<a ng-click="openPageUrl('/drive/Fertilisation?open=potasse')">open corn page</a>

In the controller, openPageUrl is as follows:

$scope.openPageUrl = function (url) {
    closePopover();
    console.log("Open page url "+url);
    $location.url(url);
};

Still in the controller, the route is handled, the controller handle $routeParam like this:

// Potential popup to open
$scope.openPopupOnLoad = $routeParams.open;
console.log("$scope.openPopupOnLoad = "+$scope.openPopupOnLoad +"; $routeParams.open = "+ $routeParams.open);

But it sounds like the controller loose the param, logs are as follows:

[Log] Open page url /drive/Fertilisation?open=potasse (kws.corn.app.js.html, line 8581)
[Log] Open page url /drive/Fertilisation (kws.corn.app.js.html, line 8581)
[Log] App controller: boots up Tue Jul 29 2014 22:54:42 GMT+0200 (CEST)
[Log] $scope.openPopupOnLoad = undefined; $routeParams.open = undefined (kws.corn.app.js.html, line 607)
[Log] App controller: already executed, won't do it again except routes (kws.corn.app.js.html, line 610)
[Log] App controller: boots up done Tue Jul 29 2014 22:54:42 GMT+0200 (CEST) (kws.corn.app.js.html, line 632)

How would you handle the param?

Upvotes: 1

Views: 1615

Answers (1)

TrazeK
TrazeK

Reputation: 838

You can set the params in the app's route config section:

app.config(function($routeProvider) {
  $routeProvider
    .when("/route1/:param", {
      template: "<div>Route #1</div><div>Route param: {{param}}</div>",
      controller: "Ctrl"
    })
    .when("/route2/:param", {
      template: "<div>Route #2 </div><div>Route param: {{param}}</div>",
      controller: "Ctrl"
    });
});

Then refer to them in links:

<a href="#/route1/param">Route 1</a>
<a href="#/route2/potasse">Route 2</a>

Access them from the controller:

app.controller("Ctrl", function($scope, $routeParams) {
  $scope.param = $routeParams.param;
});

See Plunker

Upvotes: 1

Related Questions