如何替换AngularJS指令链接函数中的元素? [英] How to replace an element in AngularJS directive linking function?

查看:85
本文介绍了如何替换AngularJS指令链接函数中的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个<row> AngularJS指令,该指令需要使用可以包含任何HTML代码的动态模板替换自身(<row>标签在执行后不得出现在DOM中).

I'm creating a <row> AngularJS directive that needs to replace itself (the <row> tag must not be present in the DOM after execution) with a dynamic template that can contain any HTML code.

使用replace: true的问题是它不能与表的<tr>标记一起使用,并且模板是动态选择的.

The problem in using replace: true is that it does not work with table's <tr> tags and that the template is dynamically chosen.

所以我试图找到一种方法来替换链接函数中的元素,但是没有成功.

So I'm trying to find a way to replace the element in the linking function, with no success.

由于未知原因,使用jQuery的.replaceWith()中断ngRepeat.

Using jQuery's .replaceWith() breaks ngRepeat for unknown reason.

有任何提示吗?

这是小提琴

推荐答案

您的小提琴看起来很基础,但是您应该可以只使用outerHTML

Your fiddle seems pretty basic but you should be able to just use outerHTML

element[0].outerHTML ='<div>I should not be red</div>';

更新了小提琴

Updated fiddle

如果必须处理ng-repeat,则可以将项绑定到scope属性,并在编译的模板中引用它们.编译后即可使用jQuery replaceWith()

If you have to deal with ng-repeat you can bind your items to a scope property and reference them in your template that you compile. Once it is compiled you can use jQuery replaceWith()

html

<row items="items">***</row>

指令

.directive('row', function ($compile) {
    return {
        restrict: 'E',
        scope: {
            items: "="
        },
        link: function (scope, element, attrs) {
            var html ='<div ng-repeat="item in items">I should not be red</div>';
            var e =$compile(html)(scope);
            element.replaceWith(e);
        }
    };
});

ng-repeat示例

这篇关于如何替换AngularJS指令链接函数中的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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