2

I have a situation in angular where I want to handle a single route that has the same pattern, but the template that is loaded for the route will be one of two different views (determined server side according to the specific route). I need to use different angular controllers for the two different views.

$routeProvider.when('/things/:whatever*.html', {
    templateUrl: function(params) {
        var info = getExtraInfo();
        return '/partials/things/' + params.whatever + '.html';
    },
    controller : ? // here's where I need to be able to choose a controller
});

I'm using a function with the templateUrl property because I need to pass on the parameter from the original route. In that templateUrl function I am retrieving extra information with which I can determine which angular controller I would like to use. Not important what that information is or where it comes from.

Unfortunately it seems like the controller needs to be set in stone when the route provider is configured.

Is there any way to handle this or do I just have to find a way to use the same controller for each case?

2
  • 2
    You can set ng-controller as an attribute in the view. Commented Jan 14, 2014 at 16:30
  • Ha! of course I can. What an idiot I am - thanks. Commented Jan 14, 2014 at 16:41

1 Answer 1

2

Just omit the controller option and let your views decide their controllers:

$routeProvider.when('/things/:whatever*.html', {
    templateUrl: function(params) {
        var info = getExtraInfo();
        return '/partials/things/' + params.whatever + '.html';
    },
    resolve:{
      users: function(){
        //return a promise
      }
    }
});

Inside view1 wrap everything with ng-controller:

 <div ng-controller="controller1">
   ...
 </div>

Inside view2 wrap everything with ng-controller:

 <div ng-controller="controller2">
   ...
 </div>

If you need access to the resolved data just inject $route:

app.controller('controller1', function($scope, $route){
   var users = $route.current.locals.users;
})
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks - so busy thinking of ingenious routing mechanisms that I didn't think of the most obvious answer!
Actually I spoke too soon - this doesn't seem to work for me because I also need to use a resolver in my route to resolve one of the controller's dependencies. It seems that the resolver doesn't get called when I specify the controller declaratively and so I get an unknown provider error. So I think I still have a problem.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.