简体   繁体   English

动态创建绑定属性的angular指令内部html重新编译

[英]angular directive inner html recompilation with creating a bind attribute dynamically

I am trying to simplify the code below, which is inside angular controller, dynamically adds attribute and recompiles directive inner html. 我试图简化下面的代码,该代码位于angular控制器内,动态添加属性并重新编译内部html指令。

additionalInfo: '=',

This attribute enables parts of the code in a template, so it must be recompiled while being dynamically created 此属性启用模板中的部分代码,因此在动态创建时必须重新编译它

$element.attr('additional-info', "'test'");
var template = angular.element('<a></a>').append($element.clone()).html();
$element.replaceWith($compile(template)($scope.$parent));

The code works fine, I am trying to distill the code to minimum, any thoughts? 代码工作正常,我正在尝试将代码精简到最低限度,有什么想法吗? Maybe something can be replaced to look nicer? 也许可以替换一些东西以使其看起来更好?

I have got two more options, which yield the same result: 我还有两个选择,它们产生相同的结果:

var template = angular.element('<a></a>').append($element.clone()).html();
var template = $element.get(0).outerHTML;
var template = $element.html($element.get(0).cloneNode(true));

All of them work correctly, but the last one is actually returning an object, but this still works? 它们都可以正常工作,但是最后一个实际上是在返回一个对象,但这仍然有效吗? How? 怎么样? Why? 为什么? Pros/Cons? 优点缺点?

First off why are you recompiling the elements in the DOM? 首先,为什么要重新编译DOM中的元素? I ask as there is likely a better solution. 我问,因为可能有更好的解决方案。

Secondly, both of the solutions you propose do not work. 其次,您提出的两种解决方案都不起作用。 Yes, they appear to give you the same results as what was displayed however if you were using two-way binding you lost that can cannot get it back. 是的,它们看起来可以为您提供与显示的结果相同的结果,但是,如果您使用双向绑定,则会丢失无法找回的信息。

Such that once <div>{{value}}</div> is resolved it will forever be the resolved values <div>SomeValue</div> . 这样,一旦<div>{{value}}</div>被解析,它将永远是解析的值<div>SomeValue</div>

To recompile the code exactally as it was then you need to precompiled DOM, which is only available in a directives compile function. 要完全按原样重新编译代码,则需要预编译DOM( 在指令编译功能中可用)。 You would need to store off that uncompiled HTML and when something occurs change it and rebuild it. 您需要存储未编译的HTML,并在发生更改时对其进行重新生成。

.directive('someDirective', function() {
    return {
        compile: function($element, $attrs) {
            var originalHtml = $element[0].outerHTML;
            return: function(scope, element, attrs) {
                // some action occurs
                var newElement = angular.element(originalHtml);
                element[0].insertBefore(newElement, element[0].parent);
                $compile(newElement)(scope);
            };
        }
    }
})

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

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