title: Compile dynamic HTML and bind variable from JSON response - Directive with Isolated scope - AngularJS
body: <p>I need to render dynamic template from database and also need to bind the variables to expressions.</p>
  
  <p>My response JSON will look like this,</p>
  
  <pre><code>[{
      "htmlTemplate": "&lt;div&gt;{{name}}&lt;/div&gt;&lt;div&gt;{{age}}&lt;/div&gt;",
      "bindData": {
          "name": "safeer",
          "age" : "25"
      }
  }, {
      "htmlTemplate": "&lt;span&gt;{{name}}&lt;/span&gt;&lt;div&gt;{{address}}&lt;/div&gt;",
      "bindData": {
          "name": "john",
          "address":"qwerty"
      }
  }, {
      "htmlTemplate": "&lt;h4&gt;{{name}}&lt;/h4&gt;&lt;h2&gt;{{country}}&lt;/h2&gt;",
      "bindData": {
          "name": "james",
          "country":"India",
          "state" : "Kerala"
      }
  }]
  </code></pre>
  
  <p>I have created a directive as per the answer to the question  <a href="https://stackoverflow.com/questions/18157305/angularjs-compiling-dynamic-html-strings-from-database">Compiling dynamic HTML strings from database</a></p>
  
  <p>In html, <strong>demo.html</strong></p>
  
  <pre><code>&lt;div dynamic="html"&gt;&lt;/div&gt;
  </code></pre>
  
  <p>In directive, <strong>directive.js</strong></p>
  
  <pre><code>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);
        });
      }
    };
  });
  </code></pre>
  
  <p>It will render html template and replace variable with <code>$scope</code> variable <code>name</code> finely.</p>
  
  <p>But I need to render each htmlTemplate with its corresponding bindData. That is render each template with isolated scope data. Need to generalize directive.</p>
  
  <p>Any help appreciated! Thanks in advance.</p>