2016-07-01 26 views
0

我想要實現類似的結果Codepen或jsfiddle,在那裏你可以鍵入一些代碼,然後執行。從字符串運行角碼

http://jsfiddle.net/Lvc0u55v/6313/

var myApp = angular.module('myApp',[]); 

// Lists all registered Directives for any angular module.. 
function Directives(module) { 
    var directives = []; 
    var invokes = angular.module(module)._invokeQueue; 
    for (var i in invokes) { 
     if (invokes[i][1] === "controller") directives.push(invokes[i][2]); 
    } 
    return directives; 
} 
myApp.controller('myCtrl',function($scope,$compile,$timeout,$rootScope,$injector){ 
    var module = "angular.module('myApp').controller('myDynamicCtrl', function($scope) {console.log('hello');window.myScope = $scope; $scope.hello = 'User!';});"; 
    (new Function(module)()); 

    // I can access the new controller via: 
    myApp._invokeQueue[1][2][1]($scope); 
    console.log(window.myScope); 

    var html = angular.element("<div ng-controller='myDynamicCtrl'; id='appended'>Hello {{hello}}</div>"); 
    angular.element(document.getElementById('target')).append(html); 

    var scope = angular.element(document.getElementById('appended')).scope(); 
    angular.element(document.getElementById('appended')).replaceWith($compile(html)(window.myScope)); 


}); 

我可以執行字符串中定義的控制器,它被正確註冊到我的角模塊。

但是,如果我將它鏈接到一個html元素,新創建的控制器是未定義的。

我想爲指令實現相同的結果(將指令定義爲字符串,執行它並編譯一個html)。

回答