如何使NG绑定,HTML编译angularjs code [英] How to make ng-bind-html compile angularjs code

查看:126
本文介绍了如何使NG绑定,HTML编译angularjs code的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我与angularjs 1.2.0-rc.3工作。我想包括HTML code到模板动态。对于我在控制器使用方法:

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);

在我的模板:

<div id="unicTab" ng-bind-html="unicTabContent"></div>

它工作正常的普通的HTML code。但是,当我试图把角模板,它不跨preTED,它只是包含在页面中。比如我想包括:

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>

非常感谢

推荐答案

此解决方案不使用硬codeD模板,你可以编译嵌入式API响应中角前pressions。

第1步
安装此指令:<一href=\"https://github.com/incuna/angular-bind-html-compile\">https://github.com/incuna/angular-bind-html-compile

第2步包含模块中的指令。

angular.module("app", ["angular-bind-html-compile"])

第3步使用该指令在模板中:

<div bind-html-compile="letterTemplate.content"></div>

结果:

JSON响应

{ "letterTemplate":[
    { content: "<div>Dear {{letter.user.name}},</div>" }
]}

输出=

<div bind-html-compile="letterTemplate.content"> 
   <div> Dear John, </div>
</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绑定,HTML编译angularjs code的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆