2016-03-29 55 views
2

我想通過AJAX加載動態HTML內容,然後編譯它,因爲它包含角度指令。如何從角度外編譯動態模板?

我有this class使用,幫助採用了棱角分明的方法沒有角控制器或指令的範圍是:

var AngularHelper = (function() { 
    var AngularHelper = function() { }; 

    /** 
    * ApplicationName : Default application name for the helper 
    */ 
    var defaultApplicationName = "MyApp"; 

    /** 
     * Compile : Compile html with the rootScope of an application 
     * and replace the content of a target element with the compiled html 
     * @$targetDom : The dom in which the compiled html should be placed 
     * @htmlToCompile : The html to compile using angular 
     * @applicationName : (Optionnal) The name of the application (use the default one if empty) 
     */ 
    AngularHelper.Compile = function ($targetDom, htmlToCompile, applicationName) { 
     var $injector = angular.injector(["ng", applicationName || defaultApplicationName]); 

     $injector.invoke(["$compile", "$rootScope", function ($compile, $rootScope) { 
         //Get the scope of the target, use the rootScope if it does not exists 
      var $scope = $targetDom.html(htmlToCompile).scope(); 
      $compile($targetDom)($scope || $rootScope); 
      $rootScope.$digest(); 
     }]); 
    } 
    return AngularHelper; 
})(); 

然後我用它在我的jQuery成功的Ajax請求後:

<!DOCTYPE html> 
<html> 
    <head> 
     <title>AngularJS Test</title> 
    </head> 
    <body> 
     <div id="contents"><!-- content --></div> 
     <script src="js/angular.js"></script> 
     <script type="text/javascript"> 
      $(document).ready(function(){ 
       $.get("http://fuiba.com/test/index.html", function(data) { 
        $("#result").html(data); 
        AngularHelper.Compile('$("#result")', data); 
       }); 
      }); 
     </script> 
    </body> 
</html> 

但我得到這個錯誤(看到這個codepen):

$targetDom.html is not a function

+1

在這一行 'AngularHelper。編譯('$(「#result」)',data);' 你傳遞字符串(''$(「#result」)'')給參數'$ ta rgetDom「,但後來在函數中,你可以像使用jQuery對象一樣通過調用'.html'函數來處理它。當然String類沒有這樣的方法。 –

+0

@RytisAlekna感謝你和MiTa,問題解決了,但我又遇到了一個錯誤。看到這[codepen](http://codepen.io/anon/pen/xVLVVv)。 –

回答

1

你需要傳遞一個DOM元素不是一個字符串作爲第一個參數AngularHelper.Compile功能,

所以

AngularHelper.Compile($("#result"), data);

AngularHelper.Compile('$("#result")', data);

+0

非常感謝你@MiTa !!該問題已解決,但我得到另一個錯誤:'模塊'MyApp'不可用!您拼錯了模塊名稱或忘記加載模塊名稱。如果註冊一個模塊,確保你指定依賴關係作爲第二個參數。[codepen](http://codepen.io/anon/pen/xVLVVv) –

+1

看看第41行'angular.module('MyApp')'你只是得到這個模塊,但你必須創建它'angular.module('MyApp',[])' – MiTa

+0

我不知道爲什麼這個_AngularHelper_類完全適用於其他人,而不適合我。我得到另一個錯誤:'$ targetDom.html(...)。scope不是函數'。我會盡力解決它!謝謝!! –