简体   繁体   English

AngularJS使用范围变量设置ng-controller

[英]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 . 我对与范围内的变量与此同样的例子设置NG-点击功能相关的问题在这里

UPDATE 更新

Girafa gave me an idea to approach this problem differently. Girafa给了我一个解决该问题的想法。 Instead of changing controllers, I chose to use one common controller with a switch statement based on a scope variable: 我没有更改控制器,而是选择使用一个基于范围变量的带有switch语句的通用控制器:

<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. 尝试使用ngRoute。 With it you can assign different controllers and templates to your root element and switch between them by changing your location. 使用它,您可以为根元素分配不同的控制器和模板,并通过更改位置在它们之间切换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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