3

Hoping someone can help me with this challenge.

I request JSON data from the server using $http.get();

The data from the server returns an object. One value in the object contains HTML markup. This markup is injected to the page using <div ng-bind-html-unsafe="content" />

Within the markup, there is a custom directive named <poll />

Using the standard AngularJS directive structure, it does not pick up the directive and link it.

How can I compile this HTML once retrieved from the server and call the link function on the directive?

Thanks!

1 Answer 1

1

The $compile service is what you want.

The $compile service can be injected into a controller or directive and invoked on a template. It will return a linking function which you can call, passing in the scope that you want to link.

Here's an example:

angular.module('app', []);

angular.module('app').controller('MainCtrl', function ($compile, $rootScope) {
  var template = '<special-directive prop="myProp"> </special-directive>';
  var scope = $rootScope.$new();
  var top = document.getElementById('top');
  scope.myProp = 'Say hello to your mother for me';
  top.innerHTML = template;
  
  $compile(top)(scope);
})

angular.module('app').directive('specialDirective', function () {
	return {
      scope:{ prop: '=' },
      restrict: 'E',
      link: function (scope, ele) {
        var html = 'Hello from the special directive<br/><br/>' + scope.prop;
        ele.html(html);
      }
    }
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="MainCtrl">
  <div id="top"></div>
</div>

Sign up to request clarification or add additional context in comments.

2 Comments

I've been looking into the $compile function but cannot get it to work :( I'm currently using $scope.content = $compile($scope.tip.data.Node.body); then <div ng-bind-html-unsafe="content" />` but nothing shows up in the template
Please see the snippet above.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.