How can you notice when a DOM element is deleted from the page?

I am in the process of creating a custom directive that will ensure only one element is active at a time.

Directive: displayOneAtATime Description: This directive can be applied to a DOM node to guarantee that only one element with this directive can be visible simultaneously.
Usage:

<body>
<div id="one" display-one-at-a-time></div>

<section> 
<div id="two" display-one-at-a-time></div>
</section>
</body>

In this scenario, "two" would be the visible element... Now picture a situation where an external event triggers a jqLite .remove() on the section element. How can I detect the removal of "two" and then show "one" again?

angular.module('SWS')
.directive('swsOneAtATime', ['$log', '$interval', function($log, $interval) {
  var elements = [];
  return function(scope, elem, attrs) {
    if (elements.length > 0) {
      _.each(elements, function(e) {
        e.css('visibility', 'hidden');
      });
    }
    elem[0].addEventListener('DOMNodeRemoved', function(ev) {
      // THIS DOM EVENT WILL NOT TRIGGER...
      if ('hidden' != elem.css('visibility')) {
        elements.splice(elements.indexOf(elem), 1);
        elements[elements.length].css('visibility', 'visible');
      }
    }, false);

    elements.push(elem);
  };
}]);

Answer №1

The recommended approach for listening in Angular is by using scope.on("$destroy", fn) https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$destroy

$scope.on("$destroy", function(event){
   // perform necessary cleanup
});

// This method can also be applied to elements
elem.on("$destroy", function(event){
   // perform required cleanup    
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to automate the selection of a dropdown menu using Selenium WebDriver

I am currently utilizing http://www.makemytrip.com/ This is the HTML code. <div class="mrgnBot30 clearFix"> <span class="watch_icn flL"></span> <div class="widget_inner clearFix suggest_me padBot15 flL"> <h3 class="clearFix has ...

Uploading large files on Vuejs causes the browser to crash

Whenever I try to upload a file using my browser (Chrome), everything goes smoothly for files with a size of 30mb. However, if I attempt to upload a file that is 150mb in size, the browser crashes. The server's maximum upload size has been configured ...

Using JavaScript to create a dynamic to-do list that persists on the browser even when refreshed

I created a Javascript Todolist that is functioning well, but I am seeking a way to ensure that my Todo-items persist on the browser even after refreshing until I choose to delete them. Any suggestions or advice on how I can achieve this? ...

Is it feasible to indent lines in a template without affecting the content alignment?

Creating a string with newlines that will be included in an email later. if (action) { description = ` Git pull request action: ${action} Git pull request for repo: ${req.body.repository.full_name} Git pull request for repo URL: ${re ...

Django view receives all data in QueryDict format when using Angular to send data

As I work with Angular 1.4.4 and Django 1.8, I encountered an issue when posting data from Angular to Django view. The data is received in the form of a whole key in the QueryDict. Upon evaluating request.POST in debug mode, it returns: <QueryDict: {u ...

I'm having some trouble with my middleware test in Jest - what could be going wrong?

Below is the middleware function that needs testing: export default function validateReqBodyMiddleware(req: Request, res: Response, next: NextFunction) { const { name, email }: RequestBody = req.body; let errors: iError[] = []; if (!validator.isEmai ...

Creating a Vue.js component that integrates a Bl.ocks.org graph

I'm a rookie in the world of D3 and I am trying to implement this cool d3 element into my Vue.js component. However, I've encountered an issue with the periodic rotation that I require not functioning properly. It seems to work initially but then ...

How come my customized directive is not taking precedence over the original methods in AngularJS?

Following the guidelines in the Angular Decorator manual (https://docs.angularjs.org/guide/decorators), I attempted to create a directive and apply decoration to it. The directive's purpose is to display the current date and time. I included a (point ...

What are some ways to implement dangerouslySetInnerHTML in conjunction with read-more-react from npm?

Is there a way to include dangerouslySetInnerHTML in a text field without receiving an error? <ReadMoreReact text={yourTextHere} min={minimumLength} ideal={idealLength} max={maxLength} readMoreText={read ...

Mastering Data Labels in ng2-chart: A step-by-step guide

Once again, I find myself battling my Angular and JavaScript challenges, each question making me feel a little less intelligent. Let me walk you through how I got here. In my most recent project, I wanted to enhance the user experience by incorporating sl ...

Adjust the scroll position when the height of a div is modified

Imagine we have a large div A with a height value and below it are other divs B, C, and more. If the user is viewing divs B or C, and A reduces its height by half, the scrolling position will remain the same. However, divs B and C will move up by that amo ...

Is there a way to convert time measurements like minutes, hours, or days into seconds in React and then pass that information to an

Currently, I am working on an application that allows users to select a frequency unit (like seconds, minutes, hours, or days) and input the corresponding value. The challenge arises when I need to convert this value into seconds before sending it to the ...

Reposition the element at the bottom of its parent element

I am facing an issue with the HTML structure in my application: <div class="work-item"> <div class="image-container"> </div> <div class="text-container"> </div> </div ...

Creating a new array in Vue.js by filtering the results of a promise iteration

Is there a way to use the splice method to insert promise values from an old array into a new one for vue reactivity? I'm encountering an issue where the newArray remains empty and does not receive any values. Check out this link for more information. ...

When the value is removed, it does not revert back to the initial filtered choices

After clearing the input, I want to display all the original li's again. The issue is that even though .value = '' clears the input, the filter remains active. I could really use some help with this as it's starting to get on my nerves ...

Tips for positioning text on the left and right sides of a div in HTML styling

I am struggling with positioning two pieces of text within a div. Despite having some styling already in place, the text is currently displaying one after the other on the left-hand side. I want to position one piece of text to the left and another to the ...

Tips for recognizing hyperlinks within a block of text and converting them to clickable links in Angular 2

My task is to create clickable links within a paragraph of strings. I tried using a custom pipe, but seem to be missing something essential. Here's my attempt: import { Pipe, PipeTransform } from '@angular/core'; import { DecimalPipe ...

Displaying JavaScript Countdown in PHP Table

I have a database table with multiple fields and I am looking to create a countdown using the integer value from one of the fields (in minutes). How can I loop through and display the countdown for each row in a PHP table utilizing these values, with the a ...

Why is Vue JS throwing an error stating "undefined is not an object"?

After creating a Vue app on a single page .html file served by django, which consists of multiple components, I decided to transition this project into a full-fledged Vue.js project using the Vue CLI. Initially, I thought it would be a simple task to trans ...

The HTML status code is 200, even though the JQuery ajax request shows a status code of 0

My issue is not related to cross site request problem, which is a common suggestion in search results for similar questions. When attempting to make an ajax request using jquery functions .get and .load, I'm receiving xhr.status 0 and xhr.statusText ...