$compile

example showing how $compile works

by Samar Pattanayak

HTML

<div ng-app="myApp">
  <div ng-controller="mainController">
    {{ message }}
    <div otc-dynamic></div>
    
  </div>
</div>

JavaScript

var app= angular.module("myApp",[]);
app.controller("mainController", function($scope){
 
    $scope.label = "Please click";
    $scope.doSomething = function(){
      $scope.message = "Clicked!";
    };
 
});
app.directive("otcDynamic", function($compile){
    return {
        link: function(scope, element){
            var el="<button ng-click='doSomething()'>{{label}}</button>";
           	var compiledEl= $compile(el)(scope);
            element.append(compiledEl);
        }
    };
});