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

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

问题描述

我正在创建一个需要替换自身的 AngularJS 指令( 标签在执行后不能出现在 DOM 中)带有可以包含任何 HTML 代码的动态模板.

使用 replace: true 的问题在于它不适用于表格的 标签,并且模板是动态选择的.

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

由于未知原因,使用 jQuery 的 .replaceWith() 会破坏 ngRepeat.

有什么提示吗?

这是小提琴

解决方案

你的小提琴看起来很基础,但你应该能够只使用 outerHTML

element[0].outerHTML ='

我不应该是红色的

';

更新小提琴

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

html

***

指令

.directive('row', function ($compile) {返回 {限制:'E',范围: {项目:="},链接:函数(范围、元素、属性){var html ='<div ng-repeat="item in items">我不应该是红色的</div>';var e =$compile(html)(scope);element.replaceWith(e);}};});

ng-repeat 示例

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.

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.

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

Any hints?

Here is the fiddle

解决方案

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

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

.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 example

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

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