自定义指令链接中的 element.replaceWith 仅在第一次调用时有效 [英] element.replaceWith in a custom directive's link only work at first time called
问题描述
我是 Angularjs 的新手,不太了解幕后的情况.基本上我想创建一个E"扭结指令,基于控制器中的数据我动态创建 html,就像一个完整的表格"一样,来替换指令.
I am new to Angularjs, and don't understand too much behind the scene. Basically I want to create an 'E' kink directive, base on the data in controller I dynamically create the html, like a whole 'table' thing, to replace the directive.
我的html文件中的指令是这样的:
The directve in my html file is like this:
<matrixrows></matrixrows>
我的指令代码是这样的:
My directive code is like this:
angular.module('matrix', [.....])
.directive('matrixrows', [..., function (...) {
return {
restrict: 'E',
replace: true,
require: '^matrix',
link: function (scope, element, attr, ctrl) {
.........
scope.$watch('currentPage', function (newValue, oldValue) {
if (newValue && newValue != oldValue) {
var html = "";
.......................
here is the code to generate the html
.......................
element.replaceWith(html);
}
});
}
}])
通过观察 currentPage 的更改,我重新创建了 html 并替换了指令标记.当我第一次更改currentPage"时,element.replaceWith(html) 工作正常.然后我更改'currentPage angin,将触发观看功能,但element.replaceWith(html) 将不起作用.
Through watching currentPage's change I recreate the html and replace the directive tag. When the first time I change 'currentPage', the element.replaceWith(html) works fine. Then I change 'currentPage angin, the watching function will be triggered, but the element.replaceWith(html) won't work.
然后进入Angularjs源码,发现第一次element.replaceWith执行后,element[0].parentNode变成了null,导致replaceWith 崩溃.
Then I stepped into Angularjs source code, I found, after the first time element.replaceWith's execution, element[0].parentNode became null, this caused the replaceWith crash.
有人知道如何使它工作吗?
Anybody know how to make it work?
推荐答案
您似乎多次尝试替换同一个元素.但是换了之后就没了.为了解决这个问题,将 currentHtml 存储在一个变量中.像这样:
It looks like you're attempting to replace the same element several times. But once it's been replaced, it's gone. To solve this store the currentHtml in a variable. Something like this:
link: function (scope, element, attr, ctrl) {
.........
var currentElement = element;
scope.$watch('currentPage', function (newValue, oldValue) {
if (newValue && newValue != oldValue) {
.......................
var html = "";
here is the code to generate the html
.......................
var replacementElement = angular.element(html);
currentElement.replaceWith(replacementElement);
currentElement = replacementElement;
}
});
}
这篇关于自定义指令链接中的 element.replaceWith 仅在第一次调用时有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!