gpt4 book ai didi

javascript - 如何让 ng-bind-html 编译 angularjs 代码

转载 作者:行者123 更新时间:2023-11-28 03:20:03 25 4
gpt4 key购买 nike

我正在使用 angularjs 1.2.0-rc.3。我想动态地将 html 代码包含到模板中。为此,我在 Controller 中使用:

html = "<div>hello</div>";
$scope.unicTabContent = $sce.trustAsHtml(html);

在我得到的模板中:

<div id="unicTab" ng-bind-html="unicTabContent"></div>

它适用于常规 html 代码。但是当我尝试放置 Angular 模板时,它不会被解释,它只是包含在页面中。例如我想包括:

<div ng-controller="formCtrl">
<div ng-repeat="item in content" ng-init="init()">
</div>
</div>

非常感谢

最佳答案

此解决方案不使用硬编码模板,您可以编译嵌入 API 响应中的 Angular 表达式。

<小时/>

第 1 步。安装此指令:https://github.com/incuna/angular-bind-html-compile

第 2 步。在模块中包含该指令。

angular.module("app", ["angular-bind-html-compile"])

第 3 步。在模板中使用指令:

<div bind-html-compile="letterTemplate.content"></div>

结果:

Controller 对象

 $scope.letter = { user: { name: "John"}}

JSON 响应

{ "letterTemplate":[
{ content: "<span>Dear {{letter.user.name}},</span>" }
]}

HTML 输出 =

<div bind-html-compile="letterTemplate.content"> 
<span>Dear John,</span>
</div>
<小时/>

为了引用,以下是相关指令:

(function () {
'use strict';

var module = angular.module('angular-bind-html-compile', []);

module.directive('bindHtmlCompile', ['$compile', function ($compile) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
scope.$watch(function () {
return scope.$eval(attrs.bindHtmlCompile);
}, function (value) {
element.html(value);
$compile(element.contents())(scope);
});
}
};
}]);
}());

关于javascript - 如何让 ng-bind-html 编译 angularjs 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59242213/

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