Reputation: 18909
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?
Upvotes: 1
Views: 484
Reputation: 4237
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>';
}
Upvotes: 0
Reputation: 60396
You need to compile your html with $compile
service:
$http.get('path/to/template')
.then(function(response){
$scope.html = $compile(response.data)($scope);
})
Upvotes: 2