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!
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.