Angular Compile new html
by Ben Clayton
HTML
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.js"></script>
<body ng-app="myApp">
<div ng-init="greeting='Hello'">{{greeting}}</div>
<div ng-controller="MainCtrl">
<input ng-model="foo" />
<div mydirective dog="bar"></div>
<div mydirective dog="foo"></div>
</div>
</body>
JavaScript
var app = angular.module('myApp', []);
app.controller('MainCtrl', function ($scope) {
$scope.foo = "hello";
$scope.bar = "World";
});
app.directive('mydirective', ['$compile', function ($compile) {
return function (scope, elem, attrs) {
//debugger;
scope.num = 1234567;
scope.jj = {
name: 'fred'
};
scope.items = [1,2,3];
//start creating an html string for our "view".
html = '<div ng-repeat="item in items">';
html += '{{item}}) {{foo | uppercase}} {{' + attrs.dog + '}} {{num | currency}} {{jj.name}}\n\n';
html += '</div>';
//create an angular element. (this is still our "view")
// angular.element() should work but didn't, so I used jquery
var el = $(html);
//compile the view into a function.
var compiled = $compile(el);
//append our view to the element of the directive.
elem.append(el);
//bind our view to the scope!
//(try commenting out this line to see what happens!)
compiled(scope);
};
}]);