AngularJS:如何从URL中删除“#!/”(bang前缀)?

10

我已经执行了$locationProvider.html5Mode(true);但它没有生效。每当我访问http://example.com,它都会跳转到http://example.com/#!/。这里是代码:

var myApp = angular.module('myApp', ['ui.router', 'ui.bootstrap']);

myApp.config(['$qProvider', function ($qProvider) {
    $qProvider.errorOnUnhandledRejections(false);
}]);

myApp.config(function($stateProvider, $urlRouterProvider,$locationProvider) {
    // For any unmatched url, redirect to EXTRANET home page
    $urlRouterProvider.otherwise('/');
    // Now set up the states
    $stateProvider
    .state('listrole', {
    url: "/list-role",
    views: {
      'main-content': {
        templateUrl: rootUrl+ 'views/main.html',
        controller: 'rolesCtrl'
      }
    }
    })
    $locationProvider.hashPrefix('');
    $locationProvider.html5Mode(true);
});

更新 我也添加了$locationProvider.hashPrefix('');,但是没有任何区别。另外告诉你,我在地址栏中输入地址并按回车键。我这样做对吗?浏览器如何发现它不需要从服务器刷新?

更新#2

理想情况下,我希望URL为http://example.comhttp://example.com/#!/list-role变成http://example.com/list-role。现在http://example.com/list-role会给出404错误。

更新#3

我正在使用nginx代理,如果有帮助的话。

更新#4

清除缓存后,现在我可以看到http://example.com,而不是http://example.com/#!,但仍然会得到404错误http://example.com/list-role


2
$locationProvider.hashPrefix('!'); - federico scamuzzi
6个回答

25
如果您想要移除这个前缀,请将以下代码添加到您的配置文件中:
appModule.config(['$locationProvider', function($locationProvider) {
  $locationProvider.hashPrefix('');
}]);

这里有更多信息。


更新

如果你想要删除整个前缀(#而不仅仅是!),你可以尝试这个解决方案

1)在模块配置中激活HTML5模式并删除前缀!

$locationProvider.html5Mode(true);
$locationProvider.hashPrefix('');

2) 然后在你的index.html文件的<head>标签中将base设为/

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

11
刷新后它无法正常工作。刷新时出现404错误。 - ojus kulkarni
2
你说的删除整个前缀(#而不仅仅是!)的方法对我不起作用。 - PHPFan
你通过这个帮我省了很多麻烦!谢谢。 - Someguy

3

在你的html文件中添加<head> <base href="/foldername/"> </head>

这是针对你的app.js的$locationProvider.html5Mode(true);

如果没有,请创建一个.htaccess文件。

RewriteEngine On 
# If an existing asset or directory is requested go to it as it is
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d  
RewriteRule ^ - [L]
RewriteRule ^ /foldername/

1

2
它不起作用。一旦我按下F5刷新根URL,它就会在其中添加。 - Volatil3
将其添加到 app.js 文件中,并添加依赖项 @Volatil3。 - Shiva

1
将以下内容添加到app.js文件中。
app.config(['$locationProvider', function($locationProvider) {

  $locationProvider.hashPrefix('');

}]);

0
如果您正在使用带有AngularJS的.NET堆栈,这是您需要执行的操作以从URL中删除“#”符号:
1.在_Layout页面中设置您的基本href:
 <head> <base href="/"> </head>

2. 然后,在你的 Angular 应用配置中添加以下内容:

$locationProvider.html5Mode(true)
$locationProvider.hashPrefix("!");

0

无需在括号中使用符号(!)@Tome - Shiva
1
@Shiva 是的,但这是重复内容。 - Tome Pejoski
@Volatil3 $locationProvider.hashPrefix(''); 添加这段代码,但我无法在您的代码中看到它。 - Shiva
页面未找到问题 - Volatil3
@Volatil3,你能否创建一个JSFiddle页面来展示你的代码? - Tome Pejoski

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接