Compiling dynamic HTML strings from database. Here is example to demonstrate how to use $compile to create a directive rendering dynamic HTML entered by users and binding to the controller’s scope. The source is posted below:
HTML Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<!DOCTYPE html> <html ng-app="app"> <head> <script data-require="[email protected]" data-semver="1.0.7" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js"></script> <script src="script.js"></script> </head> <body> <h1>Compile dynamic HTML</h1> <div ng-controller="MyController"> <textarea ng-model="html"></textarea> <div dynamic="html"></div> </div> </body> </html> |
JS Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
var app = angular.module('app', []); app.directive('dynamic', function ($compile) { return { restrict: 'A', replace: true, link: function (scope, ele, attrs) { scope.$watch(attrs.dynamic, function(html) { ele.html(html); $compile(ele.contents())(scope); }); } }; }); function MyController($scope) { $scope.click = function(arg) { alert('Clicked ' + arg); } $scope.html = '<a ng-click="click(1)" href="#">Click me</a>'; } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.