4

I have a template (for a modal popup) and depending on its function, different controllers should be loaded:

<div id="MsgBoxBack" ng-controller="{{notification.ctrl}}">

Controllers:

app.controller('MainCtrl', ['$scope', function($scope){
    $scope.notification = {
        ctrl: 'logout', 
        //...
    };
}]);

app.controller('logout', ['$scope', function($scope){
    //...
}]);

When I try to set the controller name through a scope variable, I get the following error:

Error: [ng:areq] Argument 'notification.ctrl' is not a function, got string

So how should I set a controller based on a scope variable?

PLUNKER

I have a related question about setting ng-click functions with scope variables with this very same example here.

UPDATE

Girafa gave me an idea to approach this problem differently. Instead of changing controllers, I chose to use one common controller with a switch statement based on a scope variable:

<div id="MsgBoxBack" ng-controller="notification">

Controllers:

app.controller('MainCtrl', ['$scope', function($scope){
    $scope.notification = {
        ctrl: 'logout', 
        //...
    };
}]);

app.controller('notification', ['$scope', function($scope){
  switch($scope.notification.ctrl) {
    case 'logout':
      console.log('logout');

      //...

      break;
  }

}]);

UPDATED PLUNKER

This is not solving the original question, but appears to be a simple workaround. If anyone knows of a better way doing it, just let me know, I'll be happy to update the question or accept any better answers.

1 Answer 1

0

Try using ngRoute. With it you can assign different controllers and templates to your root element and switch between them by changing your location.

Sign up to request clarification or add additional context in comments.

5 Comments

I don't want to change location, this is supposed to be a simple reusable modal window template, that shows up in different pages on the website, and needs a different controller depending on what functionality it has on that specific page..
Than I'd use different elements with ngIf or ngSwitch directives applied to them.
Or create a directive using directive definition object. And in directive function define the controller you want
Thanks, I will check these and see if I can use them!
There is a feature in angular. I haven't found it in docs. But in directive definition object you can pass string to controller parameter. So you can define your controller in a separate file and then use in your directive by simply passing its name to your directive definition object.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.