I want to load dynamic HTML content via AJAX, then compile it, because it contains angular directives.
<!DOCTYPE html>
<html ng-app="app">
<head>
<title>Compile dynamic HTML</title>
<script type="text/javascript" src="js/jquery-1.11.0.js"></script>
<script type="text/javascript" src="js/angular.js"></script>
</head>
<body ng-controller="TestCtrl">
<div obj></div>
<button class="foo">Change</button>
<script type="text/javascript">
var app=angular.module('app',[]);
app.controller('TestCtrl',function($scope){});
jQuery(document).ready(function($){
$('.foo').on('click',function(e){
// todo: load HTML content via AJAX or generate via jQuery
// todo: compile new HTML content, which contains Angular directives
});
});
</script>
</body>
</html>
We can get reference to $compile
outside of angular via injector().invoke()
.
jQuery(document).ready(function($){
$('.foo').on('click',function(e){
e.preventDefault();
angular.element(document).injector().invoke(function($compile){
var obj=$('[obj]'); // get wrapper
var scope=obj.scope(); // get scope
// generate dynamic content
obj.html($('<input type="text" ng-pattern="/^([0-9]+)$/" ng-model="test"><span>{{test}}</span>'));
// compile!!!
$compile(obj.contents())(scope);
});
});
});
Sorry, this way cannot work in my scenario.
var module = angular.module("myTest", []);
Current Page:
<html>
<head>test</head>
<body ng-app="core">
<div id="AjaxContent"></div>
<input type="button" id="loadContentButton" />
<script>
var coreModule = angular.module("core", []);module.controller("MyTestController", ["$scope", function($scope) {}]);
$(function() {
$("#loadContentButton").on("click", function() {
$.ajax({
url: "AjaxContent.html",
success: function(view) {
var ajaxContentElement = $("#AjaxContent");
ajaxContentElement .html(view);
angular.element(ajaxContentElement ).injector().invoke(["$compile", function ($compile) {
var scope = ajaxContentElement .scope();
$compile(ajaxContentElement )(scope);
scope.$apply();
}]);
}
});
});
});
</script>
</body>
Ajax Content:
<div ng-app="myTest" ng-controller="MyTestController">
this is my test page.
</div>
This will throw the js error:
Uncaught Error: [$injector:unpr] Unknown provider: lengthCountLeftFilterProvider <- lengthCountLeftFilter
Please help anyone can.Thx so much!