是否可以从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

.config(function ($routeProvider,$locationProvider)

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

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

就是这样。

其他回答

是的,你应该配置$locationProvider并设置html5Mode为true:

angular.module('phonecat', []).
  config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {

    $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);

  }]);

你可以调整html5mode,但这只适用于页面的html锚中包含的链接,以及url在浏览器地址栏中的样子。试图从页面外的任何地方请求不带标签(带或不带html5mode)的子页面将导致404错误。例如,以下CURL请求将导致一个page not found错误,与html5mode无关:

$ curl http://foo.bar/phones

虽然下面会返回根/主页:

$ curl http://foo.bar/#/phones

这样做的原因是,在请求到达服务器之前,标签之后的任何内容都会被剥离。因此,对http://foo.bar/#/portfolio的请求作为对http://foo.bar的请求到达服务器。服务器将响应http://foo.bar的200 OK响应(假设),代理/客户端将处理其余的内容。

因此,如果你想与他人分享一个url,你别无选择,只能包含这个标签。

只需添加$locationProvider

.config(function ($routeProvider,$locationProvider)

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

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

就是这样。

根据文档。你可以使用:

$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/#!/其他

如果你在。net堆栈中使用MVC和AngularJS,这是你必须做的从url中删除'#':

Set up your base href in your _Layout page: <head> <base href="/"> </head> Then, add following in your angular app config : $locationProvider.html5Mode(true) Above will remove '#' from url but page refresh won't work e.g. if you are in "yoursite.com/about" page refreash will give you a 404. This is because MVC does not know about angular routing and by MVC pattern it will look for a MVC page for 'about' which does not exists in MVC routing path. Workaround for this is to send all MVC page request to a single MVC view and you can do that by adding a route that catches all

url:

routes.MapRoute(
    name: "App",
    url: "{*url}",
    defaults: new {
        controller = "Home", action = "Index"
    }
);