AngularJS:从控制器内读取路由参数 [英] AngularJS: Read route param from within controller

查看:20
本文介绍了AngularJS:从控制器内读取路由参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

假设我有一个像 http://localhost/var/:value 这样的 URL,我希望将该值存储在 /var/的控制器内的一个变量中:值 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.

我曾尝试使用 $routeParams.value$route.current.params.value$routeParams 在开头和$route 不起作用.

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发生了路线变化,例如您的主/主/页面控制器.

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 注入控制器中的特定路由(在定义路由时由 controller 属性指定),那么它将起作用,否则您最好听一下路由服务广播的各种事件.

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.

尝试更改您的代码以使用

Try to change your code to use

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

这篇关于AngularJS:从控制器内读取路由参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆