Wa'el Jazmaty Wa'el Jazmaty - 13 days ago 4
AngularJS Question

Compile Dynamic Directive

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

scope:{data:=}

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

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', [])
  .directive('bar',
    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));
        }
      };
    }
  )
  .directive('foo',
    function() {
      return {
        restrict: 'E',
        scope: {
          data: '='
        },
        replace: true,
        template: "<div class='in'></div>",
        link: function(scope, element, attrs) {
          element.append(JSON.stringify(scope.data))
        }
      };
    }
  );
.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>
</div>