且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何替换AngularJS指令链接函数中的元素?

更新时间:2022-06-12 21:16:19

您的小提琴看起来很基础,但是您应该可以只使用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示例