AngularJS:从控制器中读取路径参数。

时间:2022-02-12 10:35:57

How can a parameter from an URL be read within an AngularJS controller?

如何在AngularJS控制器中读取URL中的参数?

Let's say I have an URL like http://localhost/var/:value and I want the value to be stored in a variable within the controller for the /var/:value URL.

假设我有一个URL,比如http://localhost/var/:value,我希望将值存储在控制器中/var/:value URL的一个变量中。

I have tried using $routeParams.value and $route.current.params.value but $routeParams is undefined at the beginning and $route doesn't work.

我试过使用$routeParams。价值和route.current.params美元。但是$routeParams在开始时没有定义,$route无效。

2 个解决方案

#1


15  

The problem is that you probably inject $routeParams or $route in a controller that is run before a route change has occurred, e.g. your main/master/page controller.

问题是,您可能在发生路由更改之前运行的控制器中注入$routeParams或$route,例如,您的主/主/页控制器。

If you inject $routeParams in a controller for a specific route (specified by the controller property when you define the route), then it will work, otherwise you're probably better of listening to the various events the route service broadcasts.

如果您为特定的路由向控制器注入$routeParams(在定义路由时由controller属性指定),那么它将会工作,否则您可能更好地侦听路由服务广播的各种事件。

Try to change your code to use

尝试更改代码以使用

$scope.$on('$routeChangeSuccess', function (ev, current, prev) {
   // ... 
});

#2


3  

Requirements: Ensure 'ngRoute' is in your app module

要求:确保“ngRoute”在你的应用模块中

Route provider set up as: http://localhost/var/:valName

Function set up as:

函数设置为:

function functionName($scope, $routeParams){$scope.value = $routeParams.valName;}

HTML view:

HTML视图:

{{value['valName']}}

#1


15  

The problem is that you probably inject $routeParams or $route in a controller that is run before a route change has occurred, e.g. your main/master/page controller.

问题是,您可能在发生路由更改之前运行的控制器中注入$routeParams或$route,例如,您的主/主/页控制器。

If you inject $routeParams in a controller for a specific route (specified by the controller property when you define the route), then it will work, otherwise you're probably better of listening to the various events the route service broadcasts.

如果您为特定的路由向控制器注入$routeParams(在定义路由时由controller属性指定),那么它将会工作,否则您可能更好地侦听路由服务广播的各种事件。

Try to change your code to use

尝试更改代码以使用

$scope.$on('$routeChangeSuccess', function (ev, current, prev) {
   // ... 
});

#2


3  

Requirements: Ensure 'ngRoute' is in your app module

要求:确保“ngRoute”在你的应用模块中

Route provider set up as: http://localhost/var/:valName

Function set up as:

函数设置为:

function functionName($scope, $routeParams){$scope.value = $routeParams.valName;}

HTML view:

HTML视图:

{{value['valName']}}