当前位置: 首页 > 科技观察

AngularJS中的友好URL:删除URL中的#

时间:2023-03-16 19:08:11 科技观察

默认情况下,AngularJS将使用#符号来路由URL。例如:http://example.com/http://example.com/#/abouthttp://example.com/#/contact很容易得到一个干净的URL并从URL中删除井号。只做两件事。配置$locationProvider设置我们的相对连接源路径$location服务在Angular中,$location服务解析地址栏中的URL并对您的应用程序进行更改,反之亦然。我强烈建议阅读Angular的官方$location文档,以了解更多关于$location服务及其提供的功能的信息。$locationProvider和html5模式(html5Mode)我们将使用$locationProvider模块,并将html5Mode设置为true。我们将在您定义Angular应用程序并配置路由时执行此操作。Angular.module('scotchy',[]).config(function($routeProvider,$locationProvider){$routeProvider.when('/',{templateUrl:'partials/home.html',controller:mainController}).when('/about',{templateUrl:'partials/about.html',controller:mainController}).when('/contact',{templateUrl:'partials/contact.html',controller:mainController});//usetheHTML5HistoryAPI$locationProvider.html5Mode(true);});什么是HTML5历史API?这是使用脚本来操纵浏览器历史记录的标准方法。有了它你可以让Angular根据前提改变页面的路由和URL。有关详细信息,有一篇不错的HTML5HistoryAPI文章。为相对链接设置为了在整个应用程序中使用相对链接,您需要添加Seta.inthedocument有很多方法可以配置这个东西,设置HTML5Mode为true会自动解析相关链接。这种方法总是适用于我的情况。如果您的应用程序根目录与url不同,例如/my-base,则使用它作为您的起始路径。对于不支持HTML5浏览历史API的浏览器,老浏览器的回调$location服务会自动回调hashbang方法。一切对你来说都是透明的,你不需要为此做任何配置。从Angular$location文档中,您可以看到回调方法及其工作原理。总结这是在Angular应用程序中获取漂亮URL并删除主题标签的简单方法。享受超级干净、超级快速的Angular应用程序!英文原文:AngularJS中的漂亮URL:从以下位置删除#Translation:http://www.oschina.net/translate/pretty-urls-in-angularjs-removing-the-hashtag