Skip to content

Instantly share code, notes, and snippets.

@john24318
Last active August 29, 2015 14:03
Show Gist options
  • Save john24318/7e6d61bfca295d93fc9a to your computer and use it in GitHub Desktop.
Save john24318/7e6d61bfca295d93fc9a to your computer and use it in GitHub Desktop.
Compile Angular template in $(document).ready
<html ng-app>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.18/angular.min.js"></script>
</head>
<body>
<div>
<div id="ctrl" ng-controller="MyController"></div>
<div id="loader"></div>
</div>
<script>
function MyController($scope, $compile) {
$scope.scopeString1 = "This is string 1";
$scope.scopeString2 = "This is string 2";
$scope.clickMe = function() {
alert("Hi!");
}
}
$('#ctrl').append(' {{ scopeString1 }} '); // Angular precompile
$(document).ready(function(){
var $newDiv = $('<div data-ng-controller="MyController"> {{ scopeString2 }} <button ng-click="clickMe();">Button</button></div>');
$("#loader").append($newDiv);
var $injector = angular.element(document).injector();
$injector.invoke(function($compile) {
var scope = angular.element($newDiv).scope();
$compile($newDiv)(scope);
//scope.$digest(); // Remember to add this line!!
});
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment