我正在使用angularjs 1.2.0-rc.3。我想动态地将html代码包含到模板中。为此,我在控制器中使用:
html = "<div>hello</div>";
$scope.unicTabContent = $sce.trustAsHtml(html);在我得到的模板中:
<div id="unicTab" ng-bind-html="unicTabContent"></div>它适用于普通的html代码。但是当我试图把角度模板,它没有解释,它只是包括在页面中。例如,我想包括:
<div ng-controller="formCtrl">
<div ng-repeat="item in content" ng-init="init()">
</div>
</div>非常感谢
发布于 2015-05-01 20:23:00
此解决方案不使用硬编码模板,您可以编译嵌入到API响应中的角表达式.
步骤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>结果:
控制器对象
$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);
});
}
};
}]);
}());发布于 2013-11-02 13:25:45
正如Vinod在他的评论中所说,最好的方法就是使用模板。我必须在常规代码之外定义一个模板,例如,我在我的index.html中添加了该代码:
<script type="text/ng-template" id="unic_tab_template.html">
<div ng-switch on="page">
<div ng-switch-when="home"><p>{{home}}</p></div>
<div ng-switch-when="form">
<div ng-controller="formCtrl">
<div ng-repeat="item in content">{{item.name}}:{{item.value}}</div>
</div>
</div>
<div ng-switch-default>an error accured</div>
</div>
</script>这个模板是有条件的,因此根据$scope.page的值,它在这3个模板之间切换(第三个模板是一个错误处理程序)。为了使用它,我有:
<div id="unicTab" ng-controller="unicTabCtrl">
<div ng-include="'unic_tab_template.html'"></div>
</div>这样,我的页面就会改变,这取决于我的$scope控制器中的unicTabCtrl。
总结一下插入angularsjs模板接缝难以实现的想法($compile接缝是解决方案,但我无法让它工作)。但是,您可以使用条件模板。
发布于 2015-01-28 21:16:05
我试着做同样的事情,然后偶然发现了这个模块。
http://ngmodules.org/modules/ng-html-compile
我只是包含了它,然后我就可以使用“ng-html-编译”而不是"ng-bind-html“。
https://stackoverflow.com/questions/19726179
复制相似问题