简体   繁体   中英

AngularJS set ng-controller with scope variables

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM