我正在使用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/19726179/