![](/img/trans.png)
[英]Is there a way to detect when a DOM node is about to be removed from the DOM?
[英]Detect when a DOM node is removed?
我正在嘗試編寫一條指令,以確保該指令的任何一個元素在任何給定時間都將保持活動狀態。
指令:showOnlyOne說明:附加到dom節點,並確保一次只能看到一個附加了該指令的dom節點。
用法:
<body>
<div id="one" show-only-one></div>
<section>
<div id="two" show-only-one></div>
</section>
</body>
在這種情況下,顯示的將是“兩個” ...現在想象一下,由於外部事件,section元素將得到一個jqLite .remove()調用。 現在,我如何檢測到“兩個”已被刪除,然后重新激活“一個”以使其顯示?
angular.module('SWS')
.directive('swsOnlyOne', ['$log', '$interval', function($log, $interval) {
var billies = [];
return function(scope, elem, attrs) {
if (billies.length > 0) {
_.each(billies, function(b) {
b.css('visibility', 'hidden');
});
}
elem[0].addEventListener('DOMNodeRemoved', function(ev) {
// THIS DOM EVENT WILL NEVER FIRE...
if ('hidden' != elem.css('visibility')) {
billies.splice(billies.indexOf(elem), 1);
billies[billies.length].css('visibility', 'visible');
}
}, false);
billies.push(elem);
};
}]);
角度聽(最佳實踐)的方式是通過scope.on("$destroy", fn)
https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$destroy
$scope.on("$destroy", function(event){
// cleanup
});
// but can also be used on elements
elem.on("$destroy", function(event){
// cleanup
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.