2
votes

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?

1
You can set ng-controller as an attribute in the view. - CD..
Ha! of course I can. What an idiot I am - thanks. - Julian Jelfs

1 Answers

2
votes

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;
})