【问题标题】:How to initialize default route in angular?如何以角度初始化默认路由?
【发布时间】:2015-12-09 00:00:34
【问题描述】:

所以我尝试在我的应用程序中使用角度路由。问题是路由“/”没有自动初始化。所以我首先转到“/”,页面的主要内容是空的(根本没有加载模板),我单击指向/settings的链接并加载设置,然后单击指向“/”的链接,这模板正确初始化的时间。那么如何让事物一开始就初始化呢?

这是我的路由配置:

 app.config(function($routeProvider, $locationProvider) {
          $routeProvider
           .when('/', {
            templateUrl: '/profile.html',
            controller: 'ProfileController',
          }).when('/profile', {
            templateUrl: '/profile.html',
            controller: 'ProfileController',
          }).when('/settings', {
            templateUrl: '/settings.html',
            controller: 'SettingsController'
          });

          $locationProvider.html5Mode({
            enabled: true,
            requireBase: false
          });
        });

我尝试从控制器调用 $location.url("/profile") 并确实有帮助,但是必须更改 url,我宁愿保留“/”

【问题讨论】:

  • 尝试删除 .when() 中的尾随逗号作为开始
  • 没有帮助。此外,据我所知,在 JS 中的属性列表中使用尾随逗号是完全可以的
  • 在某些情况下它会破坏一些东西。所以你不应该仅仅为了它而留下逗号。它只是一个指针而不是一个答案:)
  • 你有没有尝试阅读这个answer

标签: javascript angularjs


【解决方案1】:

使用otherwise({ redirectTo: "/" })

更新:这里应该是这样的

 $routeProvider
           .when('/', {
            templateUrl: '/profile.html',
            controller: 'ProfileController',
          }).when('/profile', {
            templateUrl: '/profile.html',
            controller: 'ProfileController',
          }).when('/settings', {
            templateUrl: '/settings.html',
            controller: 'SettingsController'
          }).otherwise({ redirectTo: '/' });

【讨论】:

  • 看起来我应该添加到我的代码中,但并不能真正解决这个特定问题:(
  • 我做了一个肮脏的黑客攻击......首先我配置了“否则”,然后我做了 $location.url("/whatever")。现在页面已经很好地初始化了:P
  • 只需从您的所有 templateURL 中删除“/”
  • 没有帮助。我会坚持我的解决方案,灵感来自你最初的建议 :)
猜你喜欢
  • 1970-01-01
  • 2018-04-22
  • 1970-01-01
  • 2021-08-08
  • 1970-01-01
  • 1970-01-01
  • 2017-06-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多