【问题标题】:Angular ui-router adding hash to urlAngular ui-router 向 url 添加哈希
【发布时间】:2015-02-27 15:22:14
【问题描述】:

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

这是我的设置:

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

 <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,如果可能的话,我宁愿不使用它们。谢谢!

【问题讨论】:

标签: javascript angularjs angular-ui-router


【解决方案1】:

包括$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('/');
    });

【讨论】:

【解决方案2】:

将 $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 以处理此问题(重写回根目录)。

【讨论】:

【解决方案3】:

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

定义 ui-router 状态时,url option is not required.从该文档中:

如果为这些子状态添加书签没有意义,您可能会创建一些没有 URL 的子状态。状态机像往常一样在无 url 状态之间转换,但在完成时不会更新 url。您仍然可以获得状态转换的所有其他好处,例如参数、解析和生命周期挂钩。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 2019-11-02
    • 1970-01-01
    • 2012-01-07
    • 1970-01-01
    • 2017-08-23
    相关资源
    最近更新 更多