I am trying to write a directive which will ensure that only one of its elements will remain active at any given time.
Directive: showOnlyOne Description: attaches to a dom node and ensures that only one dom node with this directive attached can be visible at a time.
Usage:
<body>
<div id="one" show-only-one></div>
<section>
<div id="two" show-only-one></div>
</section>
</body>
In this case, the one that would show would be "two"... Now imagine that due to an external event the section element gets a jqLite .remove() called on it. Now how do I detect that "two" has been removed and then reactivate "one" so it will be shown?
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);
};
}]);
The way you listen with angular (best practices) is with 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
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.