How do I make angular.js reevaluate / recompile inner html?

kornfridge picture kornfridge · Jan 31, 2014 · Viewed 44.1k times · Source

I'm making a directive that modifies it's inner html. Code so far:

.directive('autotranslate', function($interpolate) {
    return function(scope, element, attr) {
      var html = element.html();
      debugger;
      html = html.replace(/\[\[(\w+)\]\]/g, function(_, text) {
        return '<span translate="' + text + '"></span>';
      });
      element.html(html);
    }
  })

It works, except that the inner html is not evaluated by angular. I want to trigger a revaluation of element's subtree. Is there a way to do that?

Thanks :)

Answer

Tasnim Reza picture Tasnim Reza · Jan 31, 2014

You have to $compile your inner html like

.directive('autotranslate', function($interpolate, $compile) {
    return function(scope, element, attr) {
      var html = element.html();
      debugger;
      html = html.replace(/\[\[(\w+)\]\]/g, function(_, text) {
        return '<span translate="' + text + '"></span>';
      });
      element.html(html);
      $compile(element.contents())(scope); //<---- recompilation 
    }
  })