2014-09-06 70 views
-1

我有一个由Ruby on Rails服务器支持的单页AngularJS应用程序。路由定义仅仅在RESTful的滑轨route.rb配置定义,如:如何获取简单的单页面应用程序的路由参数?

http://localhost/pages/:page_id/comments/:comment_id 

客户端是没有routeProvider配置AngularJS。所以它只是一个带有视图的简单的AngularJS控制器。

当我在http://localhost/pages/:page_id/comments/:comment_id.html,我想要提取的值为:page_id:comment_id。在AngularJS中最好的方法是什么?

注:我不介意是否真的需要使用routeProvider。但在这种情况下,我只有一个templateUrl

+0

'$ routeParams'可能是最好的。但如果你不想使用'routeProvider',你可以使用'$ location'来自己解析。 – Freedom 2014-09-06 05:34:05

回答

2

$routeParams服务允许您检索当前的一组路径参数。

需要安装ngRoute模块。

路线参数是$locationsearch()path()的组合。当$route路径匹配时,会提取path参数。

请注意,$routeParams仅在路由更改成功完成后才会更新。这意味着您不能依赖$routeParams在路由解析功能中正确。相反,您可以使用$route.current.params访问新路由的参数。

例子:

// Given: 
// URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby 
// Route: /Chapter/:chapterId/Section/:sectionId 
// 
// Then 
$routeParams ==> {chapterId:'1', sectionId:'2', search:'moby'} 

more infor

编辑:

如果使用的是angular-ui-router,你可以注入$stateParams

退房这个https://github.com/angular-ui/ui-router/wiki/URL-Routing


虽然路由的确是应用程序级的URL解析一个很好的解决方案,您可能希望使用更低水平$location服务,在自己的服务或控制器注入:

var paramValue = $location.search().myParam; 

这个简单的语法将适用于http://example.com/path?myParam=someValue

$locationProvider.html5Mode(true); 

否则有看http://example.com/#!/path?myParam=someValue“Hashbang”语法是有点复杂,但对旧的浏览器工作的好处(非:但是,只有当你在HTML5模式之前配置的$locationProvider -html5兼容)。 [via:Javarome]

+0

我之前也遇到过这个网站。但事情是,我的页面只有一个页面,根本没有ng-view或templateUrl – 2014-09-06 06:04:41

+0

如果你有ui-router,那么你可以注入'$ stateParams' – 2014-09-06 06:10:21

+0

我可以没有声明ng-view吗? – 2014-09-06 06:13:03

相关问题