作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在使用 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/
我是一名优秀的程序员,十分优秀!