AngularJS设置NG-控制器范围变量 [英] AngularJS set ng-controller with scope variables

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

问题描述

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

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

控制器:

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

我对与范围内的变量与此非常相同的例子设置NG-单击功能<一个一个相关的问题href=\"http://stackoverflow.com/questions/26409981/angularjs-set-ng-click-function-with-scope-variables-within-ng-repeat\">here.

I have a related question about setting ng-click functions with scope variables with this very same example here.

更新

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

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">

控制器:

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

这是没有解决原来的问题,但似乎是一个简单的解决方法。如果有人有更好的办法知道这样做,只是让我知道,我会很乐意更新问题或接受任何更好的答案。

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.

推荐答案

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

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-控制器范围变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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