element.replaceWith在自定义指令的链接中仅在第一次调用时工作
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.
我是Angularjs的新手,在幕后不太了解。基本上我想创建一个'E'扭结指令,基于控制器中的数据我动态创建html,就像整个'table'一样,来替换指令。
The directve in my html file is like this:
我的html文件中的directve是这样的:
<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);
}
});
}
}])
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.
通过观察currentPage的更改,我重新创建了html并替换了指令标记。当我第一次更改'currentPage'时,element.replaceWith(html)工作正常。然后我改变'currentPage angin,将触发观看功能,但是element.replaceWith(html)将不起作用。
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.
然后我进入Angularjs源代码,我发现,在第一次执行element.replaceWith之后,element [0] .parentNode变为null,这导致了replaceWith崩溃。
Anybody know how to make it work?
有谁知道如何使它工作?
2 个解决方案
#1
13
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:
看起来你试图多次替换相同的元素。但一旦它被取代,它就消失了。要解决这个问题,将currentHtml存储在一个变量中。像这样的东西:
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;
}
});
}
更多相关文章
- 自定义ComboBox焦点不会切换到选择elem并且eventBubble不会停止
- Python 3.4:试图让这个模块对这个2d数组中的销售总数求和。不工作
- Python的范围函数如何工作?
- Java程序不像python程序那样工作,我不知道为什么
- 为什么分配给True / False不能像我期望的那样工作?
- Python pyexcelerate库将多个工作表写入同一个工作簿?
- 用python阐释工作量证明(proof of work)
- gsutil - 正则表达式与替代不工作
- Mac下MySQL-python安装及EnvironmentError: mysql_config not fo