ng-controller動態載入

一般情況在使用ng-controller時,會宣告如下

目前有一個需求是MainController要動態從變數載入,來使用不同的Controller, 例如:
ng-controller="vm.GetConroller() as vm"
ps:以上程式不能執行。

解決方法-使用Directive
  1. 置換html attribute
  2. $parse取得變數值
  3. $compile轉換成對應的html 例:ng-controller='SecondController as vm'

         app.directive('sgDynamicCtrl', ['$compile', '$parse', function ($compile, $parse) {
                return {
                    restrict: 'A',
                    terminal: true,
                    priority: 100000,
                    link: function (scope, elem) {
                        var name = $parse(elem.attr('sg-dynamic-ctrl'))(scope);
                        elem.removeAttr('sg-dynamic-ctrl');
                        elem.attr('ng-controller', name);
                        $compile(elem)(scope);
                    }
                };
            }]);

使用方式



參考來源

這個網誌中的熱門文章

IIS 設定只允許特定IP進入