Zword
Zword

Reputation: 6787

How to set controller dynamically for a route?

Let me give a sample code to better explain .Below is the code :

$routeProvider
  .when("/b/:param",{
    templateUrl:"main.html"
    controller:"MainCtrl"
  })
  .when("/c/:param",{
    templateUrl:"main.html"
  });

Now from the above code you can see that for one route I have specified the controller that is to be assigned to the view and for the other I didn't add the controller property so for that route there won't be any controller assigned on the page .

Now my question :

When I don't specify the controller property in the route is there any other way that I can assign the controller for that route dynamically?

What I have tried

If question still remains unclear please add a comment below this question .Thanks .

Upvotes: 2

Views: 98

Answers (1)

Estus Flask
Estus Flask

Reputation: 223259

Apparently, it is ngView directive (one of them) which is responsible for providing the route with relevant controller. And it looks like a good place for the patch. ngView directives count varied from 1 to 2 with time, the target is the last one.

app.decorator('ngViewDirective', function ($delegate, $route, $injector) {
    var ngViewHelper = $delegate[$delegate.length - 1];

    var compile_ = ngViewHelper.compile || function () {};
    var link_ = ngViewHelper.link;

    var link = function () {
        var current = $route.current;

        if (current.controllerProvider) {
            current.controller = $injector.invoke(current.controllerProvider);
        }

        link_.apply(null, arguments);
    }
    ngViewHelper.compile = function () {
        compile_.apply(ngViewHelper, arguments);
        return link;
    };

    return $delegate;
});

It provides controllerProvider parameter for the route, similar to the one from ui-router (sorry for that).

controllerProvider is basically a function that makes use of dependency injection ($route and $routeParams are surely welcome there) and returns a controller as a string, a construction function, or no controller at all (undefined).

  ...
  .when("/:id", {
    controllerProvider: function ($routeParams) {
      var controller;
      if ($routeParams.id == 'foo')
        controller = 'FooController';
      else if ($routeParams.id == 'bar')
        controller = function ($scope) { ... };
      return controller;
    }
  });

Upvotes: 1

Related Questions