簡體   English   中英

AngularJS使用范圍變量設置ng-controller

[英]AngularJS set ng-controller with scope variables

我有一個模板(用於模式彈出窗口),根據其功能,應加載不同的控制器:

<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

那么如何基於范圍變量設置控制器?

朋克

我對與范圍內的變量與此同樣的例子設置NG-點擊功能相關的問題在這里

更新

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

}]);

更新的朋克

這不能解決原始問題,但似乎是一個簡單的解決方法。 如果有人知道更好的方法,請告訴我,我很樂意更新問題或接受更好的答案。

嘗試使用ngRoute。 使用它,您可以為根元素分配不同的控制器和模板,並通過更改位置在它們之間切換。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM