Angular ui-路由器添加散列到 url

Angular ui-router adding hash to url

我正在使用 angular 和 angular-ui-router 为应用设置脚手架。我让它工作,但它似乎在我的 url 中添加了一个散列(我是本地主机上的 运行 开发人员)localhost:9000/#/test。当我登陆主页时,它只是 localhost:9000 并且它仍然提供主视图内容。如果可能的话,我想摆脱哈希。

这是我的设置:

在我的 index.html 正文中,我只有导航,然后是 ui-视图:

 <div class="row">
   <ul class="nav navbar-nav">
      <li><a ui-sref="index">Home</a></li>
      <li><a ui-sref="test">Test</a></li>
    </ul>
  </div>

  <div ui-view=""></div>

在我的 app.js 中,我只有:

angular
.module('playApp', [
'ui.router'
])
.config(function($stateProvider) {
$stateProvider
.state('index', {
    url: '',
    templateUrl: 'views/main.html',
    controller: 'MainCtrl'
})
.state('test', {
    url: '/test',
    templateUrl: 'views/test.html',
    controller: 'testCtrl'
});
});

所以当我着陆时,它很好,但是当我开始使用我设置的导航时,它将哈希添加到 url,如果可能的话我宁愿不要它们。谢谢!

包括 $locationProvider 并执行 $locationProvider.html5Mode(true); :

angular.module('playApp', ['ui.router'])
    .config(function($stateProvider, $locationProvider) {
        $stateProvider.state('index', {
            url: '',
            templateUrl: 'views/main.html',
            controller: 'MainCtrl'
        })
       .state('test', {
            url: '/test',
            templateUrl: 'views/test.html',
            controller: 'testCtrl'
        });

        $locationProvider.html5Mode(true);
    });

我里面也有一个otherwise,所以如果找不到指定的路由,它会默认返回:

angular.module('playApp', ['ui.router'])
    .config(function($stateProvider, $locationProvider, $urlRouterProvider) {
        $stateProvider.state('index', {
            url: '',
            templateUrl: 'views/main.html',
            controller: 'MainCtrl'
        })
       .state('test', {
            url: '/test',
            templateUrl: 'views/test.html',
            controller: 'testCtrl'
        });

        $locationProvider.html5Mode(true);
        $urlRouterProvider.otherwise('/');
    });

将 $locationProvider 注入您的配置并将 html5mode 设置为 true:

angular.module('playApp', [
    'ui.router'
])
.config(function($stateProvider, $locationProvider ) {
    $stateProvider
        .state('index', {
            url: '',
            templateUrl: 'views/main.html',
            controller: 'MainCtrl'
        })
        .state('test', {
            url: '/test',
            templateUrl: 'views/test.html',
            controller: 'testCtrl'
        });

    $locationProvider.html5Mode(true);

});

确保调整 .htaccess 来处理这个问题(重写回 root)。

html5Mode 有一个替代方案。但它也有缺点。

定义ui-路由器状态时,url option is not required。来自该文档:

You might create some child states without URLs, if it doesn’t make sense to bookmark those child states. The state machine transitions between url-less states as usual, but does not update the url when complete. You still get all the other benefits of a state transition such as parameters, resolve, and lifecycle hooks.

如果您不需要为某个州提供 URL 以便用户可以为这些州添加书签,则可以省略 url 选项。 URL 不会改变。