我想通過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
在這一行 'AngularHelper。編譯('$(「#result」)',data);' 你傳遞字符串(''$(「#result」)'')給參數'$ ta rgetDom「,但後來在函數中,你可以像使用jQuery對象一樣通過調用'.html'函數來處理它。當然String類沒有這樣的方法。 –
@RytisAlekna感謝你和MiTa,問題解決了,但我又遇到了一個錯誤。看到這[codepen](http://codepen.io/anon/pen/xVLVVv)。 –