0

使用 Angular,我有十几个类似于以下示例代码的路由设置。

有没有办法在保持 URL 完整的同时根据其他一些条件覆盖加载哪个模板和控制器?我的目标是显示登录页面...假设 $scope.isLoggedIn = false。我不想将 URL 更改为 /login。

SomeApp.config(['$routeProvider', function($routeProvider) {
    $routeProvider.
    when('/place', {
        templateUrl: 'routes/place.html',
        controller: 'PlaceCtrl'
    })
    .when('/test', {
        templateUrl: 'routes/test.html',
        controller: 'TestCtrl'
    });
}]);
4

2 回答 2

1

这对于 ngRoute 来说实际上是不可行的,但是使用 ui-router,您可以根据您想要的任何内容动态地提供不同的模板。

$stateProvider.state('root',
  url: '/'
  controller: 'HomePageController'
  templateProvider: [
    '$rootScope'
    '$templateCache'
    '$http'
    ($rootScope, $templateCache, $http) ->
      templateId = if $rootScope.isLoggedIn then "home-page-logged-in" else "home-page-not-logged-in"
      templateId = "/templates/#{templateId}.html"

      return $http.get(templateId, cache: $templateCache)

  ]
)

问题是,据我所知,您不能更改控制器,只能更改模板。有点臭。

于 2014-09-25T06:24:45.263 回答
1

ngRoute 是一个非常简单的库,基本上只能将 url 映射到控制器/视图。如果您想要更多的灵活性,请尝试ui-router,它具有基于状态路由的能力。

于 2014-09-25T05:52:14.803 回答