如何让 ng-bind-html 编译 angularjs 代码 [英] How to make ng-bind-html compile angularjs code
问题描述
我正在使用 angularjs 1.2.0-rc.3.我想动态地将 html 代码包含到模板中.为此,我在控制器中使用:
html = "hello";$scope.unicTabContent = $sce.trustAsHtml(html);
在我得到的模板中:
<div id="unicTab" ng-bind-html="unicTabContent"></div>
它适用于常规 html 代码.但是当我尝试放置 angular 模板时,它不会被解释,它只是包含在页面中.例如,我想包括:
<div ng-repeat="内容中的项目" ng-init="init()">
非常感谢
此解决方案不使用硬编码模板,您可以编译嵌入在 API 响应中的 Angular 表达式.
<小时>第 1 步.安装此指令:https://github.com/incuna/angular-bind-html-compile
第 2 步.在模块中包含指令.
angular.module("app", ["angular-bind-html-compile"])
第 3 步.在模板中使用指令:
结果:
控制器对象
$scope.letter = { user: { name: "John"}}
JSON 响应
{ "letterTemplate":[{内容:<span>亲爱的{{letter.user.name}},</span>"}]}
HTML 输出 =
<span>亲爱的约翰,</span>
<小时>
为了参考,以下是相关指令:
(函数(){'使用严格';var module = angular.module('angular-bind-html-compile', []);module.directive('bindHtmlCompile', ['$compile', function ($compile) {返回 {限制:'A',链接:函数(范围、元素、属性){作用域.$watch(函数(){返回范围.$eval(attrs.bindHtmlCompile);}, 函数(值){element.html(值);$compile(element.contents())(scope);});}};}]);}());
I am working with angularjs 1.2.0-rc.3. I'd like to include html code into a template dynamically. For that I use in the controller :
html = "<div>hello</div>";
$scope.unicTabContent = $sce.trustAsHtml(html);
In the template I got :
<div id="unicTab" ng-bind-html="unicTabContent"></div>
It works fine for regular html code. But when I try to put angular template it is not interpreted, it is just included in the page. For example I'd like to include :
<div ng-controller="formCtrl">
<div ng-repeat="item in content" ng-init="init()">
</div>
</div>
Thanks a lot
This solution doesn't use hardcoded templates, and you can compile Angular expressions embedded within an API response.
Step 1. Install this directive: https://github.com/incuna/angular-bind-html-compile
Step 2. Include the directive in the module.
angular.module("app", ["angular-bind-html-compile"])
Step 3. Use the directive in the template:
<div bind-html-compile="letterTemplate.content"></div>
Result:
Controller Object
$scope.letter = { user: { name: "John"}}
JSON Response
{ "letterTemplate":[
{ content: "<span>Dear {{letter.user.name}},</span>" }
]}
HTML Output =
<div bind-html-compile="letterTemplate.content">
<span>Dear John,</span>
</div>
For reference sake, here's the relevant directive:
(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);
});
}
};
}]);
}());
这篇关于如何让 ng-bind-html 编译 angularjs 代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!