【问题标题】:Removing the hash from the url in AngularJS 1.x [duplicate]从AngularJS 1.x中的url中删除哈希[重复]
【发布时间】:2018-04-02 23:05:49
【问题描述】:

我正在使用 Angular 1.x 构建一个 Web 应用程序(不使用 ionic,构建一个网站)。我想从 URL 中删除“#”。我确实实现了 html5mode true 并在 index.html 的 head 标记中放置了一个基本标记。在我刷新页面之前它工作正常。当它处于 html5mode 时,它​​认为 URL 是对服务器的请求。我正在使用 gruntjs 使用 grunt-contrib-connect 插件在本地环境中进行开发,并将我的网站托管在 Linux 托管服务器中的 GoDaddy 托管中。我想在两种环境(开发和生产)中配置 html5mode(从 URL 中删除哈希)。注意:如果在这个问题中很重要,我正在使用带有状态的 ui.router。

【问题讨论】:

标签: javascript angularjs gruntjs grunt-contrib-connect


【解决方案1】:

默认情况下,AngularJS 将使用哈希 (#) 路由 URL。

例如:

http://example.com/
http://example.com/#/about
http://example.com/#/contact

要从 URL 中删除主题标签,您需要做两件事

  • 配置$locationProvider
  • 为相对链接设置我们的基础

$位置服务

AngularJS 中,$location 服务解析地址栏中的 URL 并对应用程序进行更改,反之亦然。

$locationProvider 和 html5Mode

我们将使用$locationProvider 模块并将html5Mode 设置为true。

我们将在定义 Angular 应用程序和配置路由时这样做。

angular.module('stackoverflow', [])

.config(function($routeProvider, $locationProvider) {

    $routeProvider
        .when('/', {
            templateUrl : 'partials/home.html',
            controller : homeController
        })
        .when('/about', {
            templateUrl : 'partials/about.html',
            controller : aboutController
        })
        .when('/contact', {
            templateUrl : 'partials/contact.html',
            controller : partialController
        });

    // use the HTML5 History API
    $locationProvider.html5Mode(true);
});

设置相对链接

要使用相对链接链接应用程序,我们需要在您的文档的<head> 中设置<base>

<!doctype html>
<html>
<head>
    <meta charset="utf-8">

    <base href="/">
</head>

还有很多其他方法可以配置它,HTML5 模式设置为 true 应该会自动解析相关链接。

【讨论】:

    猜你喜欢
    • 2011-05-29
    • 2012-04-19
    • 2018-09-06
    • 2023-04-09
    • 2015-04-25
    • 2017-07-17
    • 2013-05-15
    • 2013-03-02
    相关资源
    最近更新 更多