AngularJS用作用域变量设置ng控制器

AngularJS set ng-controller with scope variables

本文关键字:ng 控制器 设置 变量 作用域 AngularJS      更新时间:2023-09-26

我有一个模板(用于模式弹出),根据其功能,应该加载不同的控制器:

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

控制器:

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

当我试图通过范围变量设置控制器名称时,我会得到以下错误:

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

那么,我应该如何根据作用域变量设置控制器呢?

PLUNKER

我有一个相关的问题,关于用范围变量设置ng-click函数,这里有一个非常相同的例子。

更新

Girafa给了我一个以不同方式处理这个问题的想法。我没有更改控制器,而是选择使用一个带有基于范围变量的switch语句的通用控制器:

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

控制器:

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;
  }
}]);

更新的PLUNKER

这并不能解决最初的问题,但似乎是一个简单的解决方法。如果有人知道更好的方法,请告诉我,我很乐意更新问题或接受任何更好的答案。

尝试使用ngRoute。使用它,您可以为根元素指定不同的控制器和模板,并通过更改位置在它们之间切换。