AngularJS Compile Example
compile on the fly, not just on page load
HTML
<div ng-app="compile">
<div ng-controller="Ctrl">
<input ng-model="name">
<br>
<button ng-repeat="n in [0,1,2]" ng-click="settmpl(n)">Template {{n+1}}</button><br/>
<textarea rows=5 cols=60 ng-model="html"></textarea>
<br>
<div compile="html"></div>
</div>
</div>
CSS
</style> <!-- Ugly Hack due to jsFiddle issue: http://goo.gl/BUfGZ --> <script src="http://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;}
body {padding:10px}
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(
function (scope) {
// watch the 'compile' expression for changes
return scope.$eval(attrs.compile);
},
function (value) {
// when the 'compile' expression changes
// assign it into the current DOM
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
console.log(scope);
console.log(element);
$compile(element.contents())(scope);
});
};
})
});
function Ctrl($scope) {
$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.settmpl = function (n) {
$scope.html = $scope.tmpls[n];
};
$scope.html = '<div ng-repeat="item in items">{{$index}}) Hello from {{name}} to {{item}}</div>';
$scope.tmpls = [
'Template 1 <br/><div ng-repeat="item in items">{{$index}}) Hello from {{name}} to {{item}}</div>{{ items.join(",") }}<br/>{{ "hello"+name | uppercase }}',
'Template 2 - Colour Squares<br/><div ng-repeat="c in colours" style="background-color:{{c}}" class="sqr"...