Angularjs:如何使用路由处理url中的参数

时间:2014-07-29 21:04:47

标签: angularjs parameters routes

我的网址方案如下:

/drive/Fertilisation?open=potasse

我进入如下页面:

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

在控制器中,openPageUrl如下:

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

仍然在控制器中处理路由,控制器处理$ routeParam,如下所示:

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

但听起来控制器松开了参数,日志如下:

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

你将如何处理这个参数?

1 个答案:

答案 0 :(得分:1)

您可以在应用程序的路线配置部分设置参数:

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

然后在链接中引用它们:

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

从控制器访问它们:

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

请参阅Plunker