AngularJS Compile template Example
compile on the fly, not just on page load
HTML
<div ng-app="compile">
<div ng-controller="Ctrl">
<input ng-model="name">
<br>Template
<button ng-repeat="n in tmpls" ng-click="settmpl($index)">{{$index+1}}</button>
<button ng-click="getpage()">Get Page</button>
<br/>
<textarea rows=5 cols=60 ng-model="html"></textarea>
<br>
<div compile="html"></div>
</div>
</div>
CSS
</style><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js">
</script><style>
.ng-invalid {
border: 1px solid red;
}
.sqr {
line-height:0px;
margin:0;
width:40px;
height:40px;
display:inline-block;
border:1px solid gray;
}
.boardrow {
line-height:0px;
}
body {
padding:10px;
}
textarea {
font-family:"Courier";
font-size:11px;
padding:4px;
}
JavaScript
// declare a new module, and inject the $compileProvider
angular.module('compile', [], function ($compileProvider) {
// configure new 'compile' directive by passing a directive
// factory function. The factory function injects the '$compile'
$compileProvider.directive('compile', function ($compile) {
// directive factory creates a link function
return function (scope, element, attrs) {
scope.$watch(
// first param is name of property in scope to watch
function (scope) {
// watch the 'compile' expression for changes
return scope.$eval(attrs.compile);
},
// second param is function to run if that property value changes.
function (value) {
// when the 'compile' expression changes
// assign it into the current DOM
debugger;
element.html(value);
// compile the new DOM and link it to the current
// scope.
// NOTE: we only compile .childNodes so that
// we don't get into infinite loop compiling ourselves
$compile(element.contents())(scope);
console.log($compile(element.contents())(scope));
});
};
})
});
function Ctrl($scope, $http) {
$scope.name = 'Angular';
$scope.total = 0;
$scope.aNumber = 1000;
$scope.items = ['Sid', 'John', 'Fred', 'Bert'];
$scope.colours = ['#FFDDDD', '#DDFFDD', '#DDDDFF'];
$scope.nums = [0, 1, 2, 3, 4, 5, 6, 7];
$scope.alt = function (n) {
return (n % 2) ? "#FFFFFF" : "#000000";
}
$scope.getscope = function () {
return $scope
};
$scope.settmpl = function (n) {
$scope.tnum = n + 1;
$scope.html = $scope.tmpls[n];
};
$scope.html = "<div ng-repeat=\"item in items\">\n{{$index}}) Hello from {{name}} to {{item}}\n</div>";
$scope.tmpls = [
'Template {{tnum}} ...