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

时间:2014-10-16 17:19:59

标签: javascript angularjs angularjs-scope

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

<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函数的相关问题,使用相同的示例here

更新

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

}]);

UPDATED PLUNKER

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

1 个答案:

答案 0 :(得分:0)

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