AngularJS 使用范围变量设置 ng-controller [英] AngularJS set ng-controller with scope variables

查看:26
本文介绍了AngularJS 使用范围变量设置 ng-controller的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

控制器:

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

当我尝试通过范围变量设置控制器名称时,出现以下错误:

错误:[ng:areq] 参数notification.ctrl"不是函数,得到的是字符串

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

PLUNKER

我有一个关于使用范围变量设置 ng-click 函数的相关问题,示例相同 此处.

更新

Girafa 给了我一个用不同方式解决这个问题的想法.我没有更改控制器,而是选择使用一个带有基于作用域变量的 switch 语句的通用控制器:

控制器:

app.controller('MainCtrl', ['$scope', function($scope){$scope.notification = {ctrl: '退出',//...};}]);app.controller('notification', ['$scope', function($scope){开关($scope.notification.ctrl){案例注销":console.log('退出');//...休息;}}]);

更新 PLUNKER

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

解决方案

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

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.

这篇关于AngularJS 使用范围变量设置 ng-controller的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆