0

Using Angular I have a dozen or so routes setup similar to the following example code.

Is there a way to override which template and controller is loaded based on some other criteria while keeping the URL in tact? My goal is to display a login page when... lets say $scope.isLoggedIn = false. I don't want to change the URL to /login.

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

2 Answers2

1

ngRoute is a very simple library that can basically only maps urls to controller/views. If you want more flexibility, try ui-router which has the ability to route based on state.

triggerNZ
  • 4,221
  • 3
  • 28
  • 34
1

This isn't really doable with ngRoute, but with ui-router you can dynamically provide different templates based on just about anything you want.

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

  ]
)

The catch is, as far as I know, you can't change the controller, only the template. Which kinda stinks.

Matt Greer
  • 60,826
  • 17
  • 123
  • 123
  • You could always put the controller in the template using ng-controller attribute though, and just exclude it from the routing altogether. :) – Stuart Sep 12 '16 at 08:54