My goal is to dynamically load HTML content using AJAX and then compile it, as it contains Angular directives.
I have a specific class that includes methods for utilizing Angular outside the scope of an angular controller or directive:
var AngularHelper = (function () {
var AngularHelper = function () { };
/**
* ApplicationName: Default application name for the helper
*/
var defaultApplicationName = "MyApp";
/**
* Compile: Compiles html with the rootScope of an application and replaces 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: (Optional) The name of the application (will 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 exist
var $scope = $targetDom.html(htmlToCompile).scope();
$compile($targetDom)($scope || $rootScope);
$rootScope.$digest();
}]);
}
return AngularHelper;
})();
Once I make a successful jQuery Ajax request, I plan to utilize this functionality:
<!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>
However, when implementing this process, I encounter the following error message (codepen link):
$targetDom.html is not a function