是否可以从angular.js的url中移除#符号?

我仍然希望能够使用浏览器的后退按钮等,当我改变视图,将更新的URL与参数,但我不想要#符号。

教程routeProvider的声明如下:

angular.module('phonecat', []).
  config(['$routeProvider', function($routeProvider) {
  $routeProvider.
  when('/phones', {templateUrl: 'partials/phone-list.html',   controller: PhoneListCtrl}).
  when('/phones/:phoneId', {templateUrl: 'partials/phone-detail.html', controller: PhoneDetailCtrl}).
  otherwise({redirectTo: '/phones'});
}]);

我可以编辑这个有相同的功能没有#吗?


当前回答

根据文档。你可以使用:

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

注意:如果您的浏览器不支持HTML 5。别担心:它有 退回到hashbang模式。因此,您不需要检查if(window。history && window.history.pushState){…手动}

例如:如果你点击:<a href="/other">某个URL</a>

在HTML5浏览器: Angular会自动重定向到example.com/other

在非HTML5浏览器中: Angular会自动重定向到example.com/#!/其他

其他回答

从index.html开始删除<a href="#/aboutus">About Us</a>中的所有#,因此它必须看起来像<a href="/aboutus">About Us</a>。现在在index.html的头标签中,在最后一个元标签之后写入<base href="/">。

现在在你的路由js中注入$locationProvider并写入$locationProvider . html5mode (true); 大概是这样的:-

app.config(function ($routeProvider, $locationProvider) {
    $routeProvider
        .when("/home", {
            templateUrl: "Templates/home.html",
            controller: "homeController"
        })
            .when("/aboutus",{templateUrl:"Templates/aboutus.html"})
            .when("/courses", {
                templateUrl: "Templates/courses.html",
                controller: "coursesController"
            })
            .when("/students", {
                templateUrl: "Templates/students.html",
                controller: "studentsController"
            })
        $locationProvider.html5Mode(true);
    });

更多细节请观看这个视频 https://www.youtube.com/watch?v=XsRugDQaGOo

只需添加$locationProvider

.config(function ($routeProvider,$locationProvider)

然后添加$locationProvider.hashPrefix("); 后

.otherwise({
        redirectTo: '/'
      });

就是这样。

这个答案假设你正在使用nginx作为反向代理,并且你已经设置了$locationProvider。Html5mode为true。

->献给那些可能还在为上面这些酷东西而挣扎的人。

当然,@maxim grach解决方案工作得很好,但对于如何响应不希望标签被包括在第一个地方的请求的解决方案,可以做的是检查php是否发送404,然后重写url。下面是nginx的代码,

在php位置中,检测404 php错误并重定向到另一个位置,

location ~ \.php${
  ...
  fastcgi_intercept_errors on;
  error_page 404 = /redirect/$request_uri ;
}

然后重写url在重定向位置和proxy_pass数据,当然,把你的网站url在我的博客的url的地方。(请求:只有在你尝试之后才会质疑这个问题)

location /redirect {
  rewrite ^/redirect/(.*) /$1;
  proxy_pass http://www.techromance.com;
}

看看魔法。

这绝对有效,至少对我来说是这样。

看来现在说这个有点晚了。但是将下面的配置添加到app.module导入中就可以了:

RouterModule.forRoot(routes, { useHash: false })

我的解决方案是创建。htaccess和使用#索里安代码。没有.htaccess,我无法删除#

RewriteEngine   On
RewriteBase     /
RewriteCond     %{REQUEST_URI} !^(/index\.php|/img|/js|/css|/robots\.txt|/favicon\.ico)
RewriteCond     %{REQUEST_FILENAME} !-f
RewriteCond     %{REQUEST_FILENAME} !-d
RewriteRule     ./index.html [L]