希望有人能帮助我应对这一挑战。
我使用$http.get()
;
来自服务器的数据返回一个对象。对象中的一个值包含HTML标记。此标记使用<div ng-bind-html-unsafe="content" />
在标记内,有一个名为<poll />
使用标准的AngularJS指令结构,它不会获取指令并链接它。
如何从服务器检索此HTML并在指令上调用链接函数?
谢谢!
答案 0 :(得分:1)
The $compile
service is what you want.
$compile
服务可以注入控制器或指令,并在模板上调用。它将返回一个你可以调用的链接函数,传入你想要链接的范围。
以下是一个示例:
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>