Cle*_*lot 52 html javascript web angularjs
我正在使用angularjs 1.2.0-rc.3.我想动态地将html代码包含到模板中.为此我在控制器中使用:
html = "<div>hello</div>";
$scope.unicTabContent = $sce.trustAsHtml(html);
Run Code Online (Sandbox Code Playgroud)
在我得到的模板中:
<div id="unicTab" ng-bind-html="unicTabContent"></div>
Run Code Online (Sandbox Code Playgroud)
它适用于常规的html代码.但是当我尝试放置角度模板时,它没有被解释,它只是包含在页面中.例如,我想包括:
<div ng-controller="formCtrl">
<div ng-repeat="item in content" ng-init="init()">
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
非常感谢
Rya*_*lay 77
此解决方案不使用硬编码模板,您可以编译嵌入在API响应中的Angular表达式.
步骤1. 安装此指令:https://github.com/incuna/angular-bind-html-compile
步骤2.在模块中包含指令.
angular.module("app", ["angular-bind-html-compile"])
Run Code Online (Sandbox Code Playgroud)
步骤3.在模板中使用该指令:
<div bind-html-compile="letterTemplate.content"></div>
Run Code Online (Sandbox Code Playgroud)
结果:
控制器对象
$scope.letter = { user: { name: "John"}}
Run Code Online (Sandbox Code Playgroud)
JSON响应
{ "letterTemplate":[
{ content: "<span>Dear {{letter.user.name}},</span>" }
]}
Run Code Online (Sandbox Code Playgroud)
HTML输出=
<div bind-html-compile="letterTemplate.content">
<span>Dear John,</span>
</div>
Run Code Online (Sandbox Code Playgroud)
为了参考,这是相关的指令:
(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);
});
}
};
}]);
}());
Run Code Online (Sandbox Code Playgroud)
Has*_*own 19
这就是我所做的,不知道它是否是角度方式TM,但它的工作原理非常简单;
.directive('dynamic', function($compile) {
return {
restrict: 'A',
replace: true,
link: function (scope, element, attrs) {
scope.$watch(attrs.dynamic, function(html) {
$compile(element.html(html).contents())(scope);
});
}
};
});
Run Code Online (Sandbox Code Playgroud)
所以;
<div id="unicTab" dynamic="unicTabContent"></div>
Run Code Online (Sandbox Code Playgroud)
编辑:我发现了角度方式,它非常简单.
$templateCache.put('unicTabContent', $sce.trustAsHtml(html));
Run Code Online (Sandbox Code Playgroud)
<div id="unicTab" ng-include="'unicTabContent'"></div>
Run Code Online (Sandbox Code Playgroud)
不需要制作自己的指令或任何东西.但它是一种绑定一次的交易,它不会像自定义指令那样对你的html做出改变.
| 归档时间: |
|
| 查看次数: |
43674 次 |
| 最近记录: |