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

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

问题描述

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

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

假设我有一个类似 http:// localhost的URL / var /:value ,我希望将该值存储在 / var /:value 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 或<$ c $在发生路由更改之前运行的控制器中的c> $ 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.

尝试更改代码以使用

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

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

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