gpt4 book ai didi

javascript - 从 JSON 文件 AngularJS 注入(inject)的编译指令

转载 作者:可可西里 更新时间:2023-11-01 14:48:00 25 4
gpt4 key购买 nike

希望有人能帮助我应对这个挑战。

我使用 $http.get() 从服务器请求 JSON 数据;

来自服务器的数据返回一个对象。对象中的一个值包含 HTML 标记。此标记使用 <div ng-bind-html-unsafe="content" /> 注入(inject)到页面中

在标记中,有一个名为 <poll /> 的自定义指令

使用标准的 AngularJS 指令结构,它不会获取指令并链接它。

如何在从服务器检索到此 HTML 后编译它并调用指令上的链接函数?

谢谢!

最佳答案

The $compile service is what you want.

$compile 服务可以注入(inject)到 Controller 或指令中并在模板上调用。它将返回一个您可以调用的链接函数,传入您要链接的范围。

这是一个例子:

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>

关于javascript - 从 JSON 文件 AngularJS 注入(inject)的编译指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25966790/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com