元素.自定义指令'中的replaceWith链接只在第一次调用时起作用
element.replaceWith in a custom directive's link only work at first time called
我是Angularjs的新手,不太了解幕后的东西。基本上,我想创建一个'E'扭结指令,基于控制器中的数据,我动态创建html,就像一个完整的'表'的东西,以取代指令。
在我的html文件中的指令是这样的:<matrixrows></matrixrows>
我的指令代码是这样的:
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', 元素。replacewith (html)工作正常。然后我改变'currentPage angin,观看功能将被触发,但元素。replacewith (html)将不起作用。
然后我进入Angularjs源代码,我发现,在第一个时间元素之后。replaceWith的执行,元素[0]parentNode变成null,这导致replaceWith崩溃。
有人知道怎么让它工作吗?
看起来您试图多次替换相同的元素。但一旦被替换,它就消失了。为了解决这个问题,将currenthhtml存储在一个变量中。像这样:
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;
}
});
}
你应该在生成的html字符串上使用$compile(…)
,
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 = $compile(html)(scope);
currentElement.replaceWith(replacementElement);
currentElement = replacementElement;
}
});
}
相关文章:
- jQueryAJAX函数被多次调用,但数据只在第一次调用时被提取
- Cordova SQLite插件仅在第一次调用时有效
- 如何在第一次调用后重新调用承诺
- jQuery:单击Ajax返回数据,但在第一次调用时显示在警报中
- 第一次调用后单击时添加类不起作用
- Jquery Jplayer 不会在我的页面中第一次调用 setMedia 函数时触发该函数
- jQuery ajax 调用未触发第一次调用
- 如何仅在第一次调用函数时执行 if 语句
- 地图标记getPosition()在第一次调用函数时不适用于谷歌地图
- Javascript函数仅在第一次调用时运行
- AJAX GET调用将在第一次调用时工作,但在其他单击之后不工作
- Ajax响应总是在第一次调用后返回2
- 第一次调用函数不会按预期工作,但下次会正常工作
- 如何处理在javascript中第一次调用终止之前被多次调用的函数
- 元素.自定义指令'中的replaceWith链接只在第一次调用时起作用
- 在html画布中第一次调用时没有加载图像
- Angularjs $http在第一次调用ng-click后不返回调用
- Button元素在第一次调用时未被检索
- Node.js/Javascript Date()命令在第一次调用后返回乱码结果
- 悬停事件在第一次调用鼠标时停止鼠标输入事件