繁体   English   中英

在Angular JS指令中编译HTML

[英]Compiling HTML in Angular JS Directive

我正在尝试为一个简单的模态窗口构建以下指令,其用法如下:

<modal content="<div class='error-text'>this is the content</div>"></modal>

哪个应生成以下标记:

<div class="modal-wrap fade-hide fade-show" ng-show="showModal" ng-click="showModal=false">
    <div class="modal-info clearfix" ng-click="$event.stopPropagation()">

        <div class='error-text'>this is the content</div>

        <button class="btn form-control" ng-click="showModal=false">OK</button>
    </div>
</div>

到目前为止,这是我的指令:

.directive('modal', function($compile){
    return {
        restrict: 'AE',
        replace: true,
        link: function(scope, element, attrs) {
            scope.content = attrs.content;
        },
        template: '<div class="modal-wrap fade-hide fade-show" ng-show="showModal" ng-click="showModal=false"><div class="modal-info clearfix" ng-click="$event.stopPropagation()">{{content}}<button class="btn form-control" ng-click="showModal=false">OK</button></div></div>',
    };
})

我遇到的问题是{{content}}没有被编译。 它被呈现为原义html。

我的模态窗口如下所示: 在此处输入图片说明

如何配置指令,以便将content属性编译为HTML?

在此示例中,我将引导程序用于模态。

请记住:在指令中,您可以使用范围代替Attr更好。

为了在您的指令中或其他地方绑定HTML,请使用ng-bind-html作为此示例

的index.html

<modal content="<div class='alert alert-danger'>this is the content</div>"></modal>

modal.html

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
                    </div>
                    <div class="modal-body" ng-bind-html="content | trust">
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                        <button type="button" class="btn btn-primary">Save changes</button>
                    </div>
                </div>
            </div>
        </div>

过滤

此过滤器可帮助您将html绑定为信任代码,我们在ng-bind-html属性的modal.html中使用它。

app.filter("trust", ['$sce', function ($sce) {
    return function (htmlCode) {
        return $sce.trustAsHtml(htmlCode);
    }
}]);

指示

app.directive('modal', function () {
    return {
        restrict: 'AE',
        templateUrl: "modal.html",
        scope: {
            content: "@"
        },
        link: function (scope, element, attrs) {
            $('#myModal').modal('show');
        }
    };
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM