The destruction of scope is not activated

Check out my issue in action with this plunkr demo. The problem I'm encountering is quite straightforward: manually calling $destroy or removing the element does not trigger the $destroy event.

function link(scope, element, attrs) {

  // Manually calling scope $destroy, however the event is not fired
  scope.$destroy();

  // Removing the element also does not trigger $destroy
  element.remove()


  scope.$on("$destroy", function handleDestroy() {
    console.log("I am destroyed")
  })
}

After reading this answer, I am even more puzzled. If element also receives a $destroy event, why do people unbind events at scope $destroy rather than element $destroy?

Answer №1

Make sure to set up the callback for the $destroy event before calling the scope.$destroy() method in your code.

Here is the corrected version:

function link(scope, element, attrs) {

  // Set up callback for scope.$destroy() event
  scope.$on("$destroy", function handleDestroy() {
    console.log("I am destroyed")
  });

  // Call scope.$destroy()
  scope.$destroy();

  // Callback for element.remove() event
  element.on('$destroy', function(){
     console.log('elem destroyed'); 
  });

  // Remove element
  element.remove();

}

Answer №2

Explore this $destroy event

app.directive("testDir", function() {
return function(scope) {
scope.$on("$destroy", function() {
  console.log("item removed");
});

};

Also, take a look at : angularjs-why-isnt-destroy-triggered-when-i-call-element-remove

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

Is it possible to place Angular Material components using code?

Currently, I'm in the process of creating a responsive Angular application. Is there any way to adjust the height and position of the <mat-sidenav-content></mat-sidenav-content> component in Angular Material programmatically without relyi ...

Is there a secure way to prevent user input from causing issues in a BigQuery node insert? Can the BigQuery.insert node library support parameterized queries for added security

I am seeking advice on how to securely insert user form data into BigQuery using the Google Cloud BigQuery library. Specifically, I am curious about the most effective methods for sanitizing, escaping, and cleaning the input data. Is it feasible to implem ...

Tips on implementing a script injected through the JS console to update form data in an Angular webpage and ensure that the changes are successfully saved

I am currently working on enhancing an existing electron app integrated with Angular. The main goal is to inject a script once the application is loaded in order to add a hotkey for efficiency. This hotkey should automatically click an edit button, input s ...

Tips for generating table headers in a dynamically adjusted table with AngularJS

I am having difficulty creating a table with dynamic height and width, specifically with the table header. The <td> elements are displaying properly using this ng-repeat: <tr ng-repeat="set in currFormData.volume track by $index"> <td ng ...

Struggling to pass express.js router requests and responses to a class method

I am struggling with setting up an Express JS router. I am facing difficulty passing req and res to my class method. Not Working app.get('/', controller.index) Working app.get('/', (res,req) => controller.index(req,res) The routi ...

Uploading multiple files and parsing them in AngularJS

I have successfully created an interface for uploading multiple CSV files. These CSV files are loaded to the client's browser using a custom fileReader service that utilizes $q, then parsed using ngPapaParser and displayed in the view with ngTable. ...

What is causing me to receive a Request Method of "GET" instead of "POST"?

I recently implemented the dropzone js library for uploading images and have a query regarding it. Is the POST method more suitable than GET when uploading an image? If yes, how can I rectify this? $(document).ready(function() { var myDropzone = new Dr ...

Establish a route nickname for files outside the project directory

I'm currently tackling a project that is divided into multiple angular projects. Within these projects, there are some services that are shared. Is there a way for me to incorporate these services into my project without encountering errors? /root / ...

transmitting an array from JavaScript to PHP

Struggling with passing an array from JavaScript to PHP for a school assignment. I'm still learning and can't seem to figure out what's missing. Any help would be greatly appreciated. This is the code I've tried: if(bets.length > ...

When making a fetch call in React, the response is the index.html file but Chrome displays an error saying Uncaught (in promise) SyntaxError: Unexpected token < in JSON

I have been encountering an issue while trying to retrieve data from my local express server and displaying it using React. The problem appears to be that instead of fetching the data, the index.html of the React app is being returned. In the network tab o ...

Static Header - Halts Animation on Downward Scroll, Resumes when Scrolling Ceases

I've implemented a fixed menu on my website. Everything seems to be working fine, but here's the issue: When I scroll down and the fixed menu starts animating, if I continue scrolling quickly, the animation pauses. It only continues when I stop ...

Break up a line within an ionic element by inserting a linebreak tag

Currently, I am constructing an app using ionic framework and facing a challenge in inserting a linebreak within an ionic tag to ensure proper display inside the designated container... <h2>{{caravan.model}}</h2> ...

Using the filter() function in jQuery allows for efficient sorting and

My current area of study is in jQuery, but I'm encountering a bit of confusion with the following code: var list = mylist.filter(function(f) { return $(f) .find('.anthing') .length > 0; }); I'm particularly puzz ...

prevent unauthorized changes to input using browser developer tools in Angular

We have a login page for our application with three fields: "user name," "password," and a "login" button. Here's the issue I'm facing: I enter a valid user name. Then, I open the Browser Developer Tools and input the following code: d ...

Accessing JSON data from an external file using AngularJS's $http method

I am new to Angular and not very comfortable with JavaScript. I am attempting to create an app using the Ionic framework. I have successfully retrieved a list from a JSON file stored in a variable, but now I am trying to use $http.get() to fetch it from a ...

Why does variable passing use 'object Text' instead of passing values?

In my for loop, I am dynamically creating a table with radio buttons and trying to create labels dynamically as well. However, when I pass the variable to the label text node, it prints out 'object Text' on the page instead of the expected value. ...

Is my utilization of the Promise feature correct?

I am currently using node to fetch data from a URL with the help of cheerio. const request=require('request'); const cheerio=require('cheerio'); const Promise = require('promise'); The function getDataParms(parm1, parm2) ret ...

What should be shown if the value is missing?"

Is it possible in Angular to display a dash "-" if there is no data in the variable o.Name using something like this: <th ng-repeat="o in Odds" >{{o.Name || "-"}}</th> Please provide a solution if available. ...

Updating the KML data on Google Maps V3 for a fresh look

I recently updated a map from V2 to V3 and I am working on incorporating code to automatically refresh the KML data every 30 seconds. The goal is to update the map with the latest data and display a countdown until the next refresh. Here is an example of ...

What are some methods for altering ReadOnly values?

I am encountering an issue with the value fetchOptions: Readonly<HttpFetchOptionsWithPath> and my attempt to overwrite one of its properties. Here is the method I have tried: ((fetchOptions as Writable<HttpFetchOptionsWithPath>).headers as Wr ...