源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

移除AngularJS下URL中的#字符的方法

  • 时间:2022-04-16 01:43 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:移除AngularJS下URL中的#字符的方法
AngularJS 默认将会使用一个 # 号来对URL进行路由. 例如:     http://example.com/     http://example.com/#/about     http://example.com/#/contact 要获得干净的URL并将井号从URL中移除是很容易的. 完成两件事情就行了. [list=1] [*]    配置 $locationProvider[/*] [*]    设置我们的相对连接的起点路径[/*] [/list] [b]$location 服务[/b] 在Angular中, $location服务会解析地址栏中的URL,并对你的应用程序作出改变,反之亦然. 我强烈推荐通读官方的 Angular $location 文档 以对$location 服务及其所提供的特性有一个了解. [b]$locationProvider 和 html5 模式(html5Mode)[/b] 我们会使用 $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
   });
  
  // use the HTML5 History API
  $locationProvider.html5Mode(true);
 });
什么是 HTML5 History API? 它是使用一个脚本来操作浏览器历史的标准方法. 有了它就能在不刷新页面的前提下让 Angular 改变路由和页面的URL. 更多的信息,这里有一篇蛮好的 HTML5 History API 文章. [b]为相对链接设置<base> [/b] 为了在应用程序各处使用相对链接,你将需要在你文档的<head>里面设置一个<set>.  
<!doctype html>
<html>
<head>
 <meta charset="utf-8">
 
 <base href="/">
</head>
有大量的方法可以用来配置这个东西,而将HTML5Mode设置为true就会自动的解析相对链接了. 在我这儿这种方式总是能起效. 如果你应用程序的根同url相比有所不同,例如 /my-base, 那就用那个作为你的起点路径. [b]老浏览器的回调[/b] $location服务对不支持HTML5浏览历史API的浏览器将自动回调hashbang方法。 一切的发生对你是透明的,你不需为此做任何配置。从[url=http://docs.angularjs.org/guide/dev_guide.services.$location]Angular $location[/url]文档中,你可以看到回调的方法已经它是如何工作的。 [img]http://files.jb51.net/file_images/article/201506/2015619153430123.jpg?2015519153443[/img] [b]总结[/b] 这是一个在Angular应用中获得漂亮URL并删除哈希标记的简单方法。享受超洁净、超快速的Angular应用吧!
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部