1

I'm calling a API that returns HTML, containing some code tags.

I'm looking forward to decorate that element with a directive, but as the HTML is coming from the API, I unable to add an directive attribute.

Angular decorates elements such as form with directives so I though about doing something like that:

angular.module('myApp')
.directive('code', function($log) {

  return {
    restrict: 'E',
    link: function(scope, element, attrs) {
      $log.info('Code Directive');
    }
  };

});

Although the console log did not print. Am I missing something?

EDIT: I notice that the log works with code elements that are created before the API call. However when the API injects the code into the html, the directive doesn't run. Is there a way to manually make it run?

jviotti
  • 17,881
  • 26
  • 89
  • 148

2 Answers2

2

You need to compile your html with $compile service:

$http.get('path/to/template')
  .then(function(response){
    $scope.html = $compile(response.data)($scope);
  })
Stewie
  • 60,366
  • 20
  • 146
  • 113
0

If your code is coming from an API, it's probably being added to your page after Angular has compiled it -- meaning that the directive isn't wired into the page.

In order to make it work, you should $compile your new html after inserting it. See: Compiling dynamic HTML strings from database, and in particular the answer: https://stackoverflow.com/a/18157958/149060

Which has:

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);
      });
    }
  };
});

function MyController($scope) {
  $scope.click = function(arg) {
    alert('Clicked ' + arg);
  }
  $scope.html = '<a ng-click="click(1)" href="#">Click me</a>';
}
Community
  • 1
  • 1
Pauli Price
  • 4,187
  • 3
  • 34
  • 62