Anri
Anri

Reputation: 6265

Dynamic controller with "controller as" syntax

If I want to assign dynamic controller, I can do the following:

<div ng-controller="MainController">
  <div ng-controller="dynamicController"></div>
</div>

function MainController($scope){
  $scope.dynamicController = MyCtrl;
  $scope.instanceName = "ctrl"; // we'll use this later
}

function MyCtrl(){}

What can I do to make this work with the new "controller as" syntax?

This works fine: <div ng-controller="dynamicController as ctrl"></div>

But how to make ctrl dynamic too? Let's say I want it to have a name that $scope.instanceName holds.

Fiddle: http://jsfiddle.net/ftza67or/2/

There is an idea to make a custom directive that will create and compile html string, but it's an ugly way, let's pretend it does not exist.

Upvotes: 1

Views: 383

Answers (2)

Anri
Anri

Reputation: 6265

So I've looked into angular sources and found this. https://github.com/angular/angular.js/blob/bf6a79c3484f474c300b5442ae73483030ef5782/src/ng/controller.js

 if (isString(expression)) {
    match = expression.match(CNTRL_REG),
    constructor = match[1],
    identifier = identifier || match[3];
    expression = controllers.hasOwnProperty(constructor)
        ? controllers[constructor]
        : getter(locals.$scope, constructor, true) ||
            (globals ? getter($window, constructor, true) : undefined);
  .... and so on

Basically, ng-controller directive currently accepts strings or expressions, if it is an expression, it has to be a controller function reference. If it is a string, well, it will take identifier name as it was passed and I don't see any way to make it evaluate a variable with dynamic expression name.

Upvotes: 0

Explosion Pills
Explosion Pills

Reputation: 191739

This should work pretty much the same, but just remember that when you use controller as you can bind properties to this inside the controller to have them accessed by the scope/view.

function MainController ($scope) {
  $scope.dynamicController = MyCtrl;
  }

function MyCtrl($scope) {
  this.foo = "baz";
  }
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
<div ng-controller="MainController">
  <div ng-controller="dynamicController as ctrl">
    {{ctrl.foo}}
  </div>
</div>

Upvotes: 1

Related Questions