Wa'el Jazmaty Wa'el Jazmaty - 1 year ago 68
AngularJS Question

Compile Dynamic Directive

Assume i've directive 'test' which has an isolated scope as


and i've another directive has link function as the following

link : function (scope,ele,att){
var testData = {bla:123};
var a = $compile(<test data = testData></test>)(scope)


so the question is how to pass testData Object to test Directive

Answer Source

Compiled element takes the scope you pass in so add to the parent scope the data you need inside the child directive:

scope.data = toFoo
element.append($compile("<foo data='data' />")(scope))

Take a look at the example

angular.module('myApp', [])
    function($compile) {
      return {
        restrict: 'A',
        link: function(scope, element, attrs) {
          var toFoo = {
            s: 'ome',
            d: 'ata'
          scope.data = toFoo
          element.append($compile("<foo data='data' />")(scope));
    function() {
      return {
        restrict: 'E',
        scope: {
          data: '='
        replace: true,
        template: "<div class='in'></div>",
        link: function(scope, element, attrs) {
.out {
  height: 100px;
  width: 200px;
  z-index: 1;
  background-color: #ddd;
  position: relative;
.in {
  height: 50px;
  width: 150px;
  z-index: 2;
  background-color: #333;
  position: absolute;
  margin: auto;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  color: white;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
  <div class="out" bar></div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download