【问题标题】:Angularjs ui router ui-sref generate wrong urlAngularjs ui路由器ui-sref生成错误的url
【发布时间】:2015-09-03 22:25:09
【问题描述】:

试图在子视图之间切换,但是当另一个子视图已经加载时,ui-sref 会生成错误的 url。 正确的链接:'template/viewname.html' 实际链接:'home/template/viewname.html' 如何阻止 ui-sref 将 'home/' 添加到链接? 谢谢

应用程序

 angular.module('app',[,'ngRoute','ui.router']);

配置

angular.module('app').config(['$urlRouterProvider', '$stateProvider',    '$locationProvider', function ($urlRouterProvider, $stateProvider,    $locationProvider) {
   $locationProvider.html5Mode({
    enabled: true,
    requireBase: false
});
$urlRouterProvider.otherwise('/');

$stateProvider.state('home', {
    url: '/home',
    templateUrl: 'template/index.html',
    controller: 'contr'

})
.state('home.about', {
    parent:'home',
    url: '/about',
    templateUrl: 'template/about.html',
    controller: 'contr'

})
.state('home.contact', {
    parent: 'home',
    url: '/contact',
    templateUrl: 'template/contact.html',
    controller: 'contr'

})  }]);

首页

<!DOCTYPE html>
<html>
 <head>
 <title></title>
 <meta charset="utf-8" />
</head>
<body>
 <h3>Home</h3>
   <div>
     <a ui-sref="home.about">abouttt</a>
     <a ui-sref="home.contact">contact</a>
   </div>
   <div ui-view>
  </div>
 </body>
</html>

【问题讨论】:

    标签: angularjs angular-ui-router


    【解决方案1】:

    你是在踢自己的脚:

    • 您将 requireBase 设置为 false,而不是使用默认值。 base 标记的原因恰恰是它允许将相对 URL 视为相对于基本 URL,而不是相对于当前 URL
    • 尽管您选择不使用基本标记,但您仍然使用相对 URL,而不是绝对 URL(即以 `/ 开头的 URL,因此无论当前位置是什么,它始终指向同一个位置)。

    有关详细信息,请参阅https://docs.angularjs.org/guide/$location#relative-links。

    【讨论】:

      【解决方案2】:

      只是一个小plnkr:http://plnkr.co/edit/RbjGt8zhAGSRb00idkEU?p=preview

      var app = angular.module('plunker', ['ui.router'])
      .config(['$stateProvider', '$urlRouterProvider','$locationProvider', function($stateProvider, $urlRouterProvider, $locationProvider) {
         $locationProvider.html5Mode({
          enabled: true,
          requireBase: false
       })
      
        $stateProvider.state('home', {
          url: '/home',
      })
      .state('home.about', {
          parent:'home',
          url: '/about',
         views:{
            '@':{
              'templateUrl': '/tpl1.html'
            }
          }
          //controller: 'contr'
      
      })
      

      【讨论】:

        【解决方案3】:

        我建议在您的 templateUrl 中使用绝对 URL,即带有前导斜杠。例如:

        $stateProvider.state('home', {
            url: '/home',
            templateUrl: '/template/index.html',
            controller: 'contr'
        });
        

        【讨论】: