Dynamically add directives

Dynamically add HTML Element with AngularJS directives

by Alexander Emashev

HTML

<script src="https://code.jquery.com/jquery-2.2.1.min.js"></script>
<div ng-app="testApp" class="box" ng-controller="addWorkOrder">
  <div class="box-header with-border">
    Dynamically add Angular directives
  </div>
  <div class="box-body">
    <div class="form-group" id="add_wl_div">
      <button type="" class="btn bg-olive pull-right" ng-click="click_addwo()">Add</button>
    </div>
    <div id="wo_container">
    </div>
  </div>
  <!-- /.box-body -->
</div>
<!-- /.box -->

JavaScript

var app = angular.module('testApp', []);

app.controller('addWorkOrder', ['$scope', '$rootScope', '$http', '$compile',
  function($scope, $rootScope, $http, $compile) {

    $scope.click_addwo = function() {
      l = '<button type="" ng-click="attachedFunct()">Click Me!</button>';
      $('#wo_container').append($compile(l)($scope));
    };
    
    // Function that will be used by dynamically added element.
    $scope.attachedFunct = function() {
      alert('Clicked attached function');
    };
  }
]);