Angular ui-router将hash添加到url

时间:2015-02-27 15:22:15

标签: javascript angularjs angular-ui-router

我正在为具有角度和角度ui路由器的应用程序设置脚手架。我有它的工作,但似乎是在我的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'
});
});

所以当我降落时,它很好,但是当我开始使用我设置的导航时,它会将散列添加到网址中,如果可能的话,不希望使用它们。谢谢!

3 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

将$ 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)。

答案 2 :(得分:0)

html5Mode的替代方案。但它有它的缺点。

定义ui-router状态时,url option is not required。从该文件:

  

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

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

相关问题