如何在Angular JS中获取URL段? [英] How to get URL segment in Angular JS?

查看:74
本文介绍了如何在Angular JS中获取URL段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在项目中具有以下网址:

I have URL's in project as:

http://blo.c/news http://blo.c/video

如何从这些URL获取细分newsvideo?

How I can get segments news, video from these URL?

我尝试在Angular JS中使用$location,但是此对象没有这些段

I tried to use $location in Angular JS, but this object has not these segments

推荐答案

您需要使用 $ location.path()

// given url http://blo.c/news
var path = $location.path();
// => "/news"

如果您使用的是HTML5模式,则必须确保 $ locationProvider.html5Mode(true)已设置,因此$location正常工作.

If you are using HTML5 mode you must ensure $locationProvider.html5Mode(true) is set so $location works properly.

如果您未使用HTML5模式(此处就是这种情况);那么您需要使用传统javascript 到获取URL,因为您首先没有使用Angular路由:

If you are not using HTML5 mode (which is the case here); then you'll need to drop to traditional javascript to get the URL, since you are not using Angular routing in the first place:

// given url http://blo.c/news
var path = window.location.pathname;
// => "/news"

您可以选择注入 $ window 而不是使用window直接来说,这只是原生window对象的一个​​薄包装,但是便于测试.

You might choose to inject $window instead of using window directly, this is only a thin wrapper over the native window object but facilitates testing.

这篇关于如何在Angular JS中获取URL段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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