angular ng-bind-html 和其中的指令 [英] angular ng-bind-html and directive within it

查看:23
本文介绍了angular ng-bind-html 和其中的指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Plunker 链接

我有一个元素,我想将 html 绑定到它.

那行得通.现在,除此之外,我还有一个绑定到绑定 html 的指令:

$scope.details = '成功!<a href="#/details/12" upper>details</a>'

但是带有 div 和锚点的指令 upper 不求值.我如何使它工作?

解决方案

我也遇到了这个问题,在网上搜索了几个小时后,我阅读了@Chandermani 的评论,事实证明这是解决方案.您需要使用此模式调用编译"指令:

HTML:

<div compile="details"></div>

JS:

.directive('compile', ['$compile', function ($compile) {返回函数(范围,元素,属性){范围.$watch(功能(范围){//观察 'compile' 表达式的变化返回范围.$eval(attrs.compile);},功能(值){//当 'compile' 表达式改变时//将其分配到当前 DOMelement.html(值);//编译新的 DOM 并将其链接到当前的//范围.//注意:我们只编译 .childNodes 以便//我们不会进入无限循环编译自己$compile(element.contents())(scope);});};}])

你可以看到一个有效的在这里

Plunker Link

I have a element which I would like to bind html to it.

<div ng-bind-html="details" upper></div>

That works. Now, along with it I also have a directive which is bound to the bound html:

$scope.details = 'Success! <a href="#/details/12" upper>details</a>'

But the directive upper with the div and anchor do not evaluate. How do I make it work?

解决方案

I was also facing this problem and after hours searching the internet I read @Chandermani's comment, which proved to be the solution. You need to call a 'compile' directive with this pattern:

HTML:

<div compile="details"></div>

JS:

.directive('compile', ['$compile', function ($compile) {
    return function(scope, element, attrs) {
        scope.$watch(
            function(scope) {
                // watch the 'compile' expression for changes
                return scope.$eval(attrs.compile);
            },
            function(value) {
                // when the 'compile' expression changes
                // assign it into the current DOM
                element.html(value);

                // compile the new DOM and link it to the current
                // scope.
                // NOTE: we only compile .childNodes so that
                // we don't get into infinite loop compiling ourselves
                $compile(element.contents())(scope);
            }
        );
    };
}])

You can see a working fiddle of it here

这篇关于angular ng-bind-html 和其中的指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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