javascript 使用 ui-router 时如何去掉 /#/?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25596941/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 04:42:54  来源:igfitidea点击:

How do I get rid of the /#/ when using ui-router?

javascriptangularjsroutesangular-ui-router

提问by gjanden

I am new to Angular and I am currently doing my routes with ui.router and was curious about something. I notice when I go to my site either on localhost or online, my URL includes /#/ at the end of it. Home looks like domain.com/#/ and other pages follow suite ( domain.com/#/about ) How do I make it appear without the hash?

我是 Angular 的新手,我目前正在使用 ui.router 做我的路线,并且对某些事情感到好奇。我注意到当我在本地主机或在线访问我的站点时,我的 URL 包含 /#/ 在它的末尾。首页看起来像 domain.com/#/ 和其他页面跟随套件 ( domain.com/#/about ) 如何让它在没有哈希的情况下出现?

Here is an example of my app.js

这是我的 app.js 的一个例子

var app = angular.module('dashboardApp', ['ui.router']);

app.config(
    ['$stateProvider','$urlRouterProvider', 
    function($stateProvider, $urlRouterProvider){
    $urlRouterProvider.otherwise('/');

    $stateProvider
        //Dashboard states and nested views ========================
        .state('home', {
            url: '/',
            templateUrl: './templates/main/dashboard.html',
            controller: 'dashboardCtrl'
        })

        //Subject states and nested views ==========================
        .state('about', {
            url: '/about',
            templateUrl: './templates/main/about.html',
            controller: 'aboutCtrl'
        });
    }]);

And here is how I am calling it in my DOM

这是我在 DOM 中调用它的方式

<div class="main-nav">
    <a ui-sref="home"><img src="randomimage.png" /></a>
</div>
<div class="main-nav">
    <a ui-sref="about">About</a>
</div>

回答by kriskova

The hasbang is there for compatibility reasons with the older browsers. Here is a thread for the same question:

hasbang 是出于与旧浏览器兼容的原因。这是同一个问题的线程:

AngularJS routing without the hash '#'

没有散​​列“#”的 AngularJS 路由

And here is a blog post explaining how to get rid of the hashbang safely with fallback for older browsers:

这是一篇博客文章,解释了如何通过旧浏览器的回退安全地摆脱 hashbang:

http://scotch.io/quick-tips/js/angular/pretty-urls-in-angularjs-removing-the-hashtag

http://scotch.io/quick-tips/js/angular/pretty-urls-in-angularjs-removing-the-hashtag

Essentially, you can use $locationProvider.html5Mode(true)to eliminate the hashbang for the "HTML5 ready" browsers and Angular will fall back automatically to the hashbang version for the older browsers.

本质上,您可以使用$locationProvider.html5Mode(true)消除“HTML5 就绪”浏览器的 hashbang,Angular 将自动回退到旧浏览器的 hashbang 版本。