【问题标题】:AngularJS: Removing the "#" with history.pushState()AngularJS:使用 history.pushState() 删除“#”
【发布时间】:2014-09-22 06:46:18
【问题描述】:

我正在尝试美化我的 Angularjs 应用程序中的 url,但我的成功有限——我可以到达 "/" 路由,但就是这样,"/about" 无法到达。

注意:该项目位于 (localhost/myngapp)。

index.html

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <base href="myngapp">
    <script  type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.12/angular.js"></script>
    <script  type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.12/angular-route.js"></script> 
    <script  type="text/javascript" src="http://localhost/myngapp/public/js/app.js"></script>   
</head>

<body data-ng-app="demoApp">
    <div data-ng-view></div>
</body>

</html>

app.js

angular.module('demoApp', ['ngRoute'])
    .config(function ($routeProvider, $locationProvider) { 
        $locationProvider.html5Mode(true); 
        $routeProvider
             .when('/', {
                 controller: 'homeCtrl',
                templateUrl: 'home.html'
             })         
             .when('/about', {
                 controller: 'aboutCtrl',
                 templateUrl: 'about.html'
             })     
            .otherwise({ redirectTo: '/' });       
    })
    .controller('homeCtrl', function ($scope) {
         $scope.title = 'This is, the App!';
    })
    .controller('aboutCtrl', function ($scope) {
         $scope.title = 'About App!';
    });

.htaccess

<ifModule mod_rewrite.c>
    RewriteEngine on

    RewriteCond %{REQUEST_FILENAME} -f [OR]
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^ - [L]
    RewriteRule ^ index.html [L]

</ifModule>

console.log (http://localhost/myngapp/ || http://localhost/myngapp/about)

【问题讨论】:

  • 如果重定向到 /about 会发生什么?你看到 about.html 了吗?
  • 您将要包装 html5mode 以检查不支持 HTML5 历史 API 的浏览器。 Supported Browsers
  • @Malkus 你说得对,我会用modernizr 和polyfill 用history.js 做检查。它有一个适用于 HTML 4 浏览器的 hashbang 回退。

标签: javascript ajax angularjs .htaccess pushstate


【解决方案1】:

已解决:&lt;base&gt; 是罪魁祸首

<head>
  <script>
    document.write('<base href="' + document.location + '" />');
  </script>
</head>

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

【讨论】:

  • 我正要告诉你,你需要设置一个RewriteBase 指令。它看起来很有效,在你的 .htaccess 中,只需将它放在顶部(在RewriteEngine On 之后)即可获得RewriteBase /myngapp/ #rest of code#
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-21
  • 2017-09-18
相关资源
最近更新 更多