Are memory leaks a common issue with Angular directives?

Using a simple html file to replicate a memory leak:

<!doctype html>
<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.6/angular.min.js"></script>
        <script>
            var app = angular.module('testApp', []);

            app.directive('directive1', function() {
                return {
                    template: '<div directive2></div>',
                    scope: true
                };
            });

            app.directive('directive2', function () {
                function LeakObject() {}

                function Foo() {
                    this.bar = function($scope) {
                            $scope.nottheredude;
                    };
                }

                return {
                    scope: true,
                    link: function($scope) {
                            $scope.memoryThatLeaks = new LeakObject();

                            new Foo().bar({});
                            new Foo().bar($scope);
                    }
                };
            });
        </script>
    </head>
    <body ng-app="testApp">
        <button ng-click="show = !show">Toggle</button>
        <div ng-if="show">The directive <div directive1></div></div>
        <div ng-if="!show">Nothing</div>
    </body>
</html>

Directive creating a new scope with another directive in its template.

Another directive performing a strange action, identified as the cause of the leak.

Main HTML toggling between nothing and directive1.

The created object on $scope, LeakObject, should be garbage collected when toggling back to nothing but remains allocated according to Chrome's heap snapshot tool.

Attempting to understand why this occurs, especially when commenting out the statement in the bar method prevents it.

Steps to reproduce:

  1. Open this file in incognito
  2. Open dev tools and navigate to Profiles
  3. Refresh the page
  4. Click Toggle twice to display Nothing
  5. Take a heap snapshot
  6. Filter for 'leak' to observe the persisting LeakObject

This is how it should look like:

If anyone can assist or provide an explanation, it would be greatly appreciated.

Answer №1

After following the provided steps, I am happy to report that everything is functioning as anticipated. No memory leaks were detected in the snapshot.

To ensure that the directive is being properly destroyed, you can include the following code snippet in the link function:

Controllers and directives emit an event just before they are destroyed. This provides an opportunity for you to clean up any plugins, listeners, or perform necessary garbage collection tasks. To do this, subscribe to the $scope.$on('$destroy', ...) event.

$scope.$on('$destroy',function(){
  //$scope.memoryThatLeaks = null;
  alert('!');
 });

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

The onsubmit event in Javascript activates the parent's onclick event

On my HTML page, I have a table with a form in each row. Clicking on the row should open a detail page, but clicking within the form should not trigger this action. Here is an example of what my row looks like: <tr onclick="window.parent.location.href ...

JQuery animations not functioning as expected

I've been attempting to create a functionality where list items can scroll up and down upon clicking a link. Unfortunately, I haven't been able to achieve the desired outcome. UPDATE: Included a JSFiddle jQuery Code: $(document).ready(function ...

Is it possible to apply styles to the body of a document using styled-components?

Is it possible to apply styles from styled-components to a parent element, such as the <body> tag, in a way that resembles the following: const PageWrapper = styled.div` body { font-size: 62.5%; } ` ...

`json object allows for category selection in options`

Hello (please excuse my English), I have the following script: <script type="text/javascript"> $(document).ready(function() { var idPlato = decodeURI(getUrlVars()["idPl"]); var url = "http://localhost/plato-datos.php?idPla="+idPl ...

In the template, I utilize both vue-router and jQuery. However, there seems to be an issue with $(document).ready() not functioning

Looking for guidance on using jQuery in Vue. I've noticed that when I refresh the page, $(document).ready() function is triggered. However, when I use vue-router to switch pages, $(document).ready() does not seem to work. <template> <div ...

Is it possible for a Vue.js build to encounter errors due to unregistered components?

Exploring a component template... <template> <Unknown></Unknown> </template> In the context of this template, Unknown could be either a globally registered component or not. Upon encountering this scenario at runtime, an informa ...

Tips for adjusting the Material UI Tabs indicator's position with react-scroller

My customized MaterialUI Tabs component stacks all tab content for scrolling using react-scroller. The tabs work smoothly except the indicator does not update its position. The react scroller has props like onSetActive, onSetInactive, and activeClass whic ...

When using Vue2, pushing a string to an array simply replaces the existing string instead of appending it

My current task involves manipulating a local data array by adding and removing strings within a method. However, I have noticed that my logic always results in the array containing only a single string passed to the updateIdArr method. Even after removin ...

What is the process of editing a webpage to affect the display on a different webpage?

I am currently working on creating two webpages. One will serve as a customization page where users can upload images and input text, which will then be displayed on another page. I am wondering if it is possible to achieve this functionality using CSS and ...

Is it possible to refresh data efficiently using web scraping tools, similar to how it

While researching web scraping in Python, I consistently found references to BeautifulSoup and Selenium as the primary tools for retrieving HTML and JavaScript content from websites. One thing that has eluded me is finding a method to automatically update ...

Ways to adjust timestamps (DayJs) by increments of 1 minute, 5 minutes, 15 minutes, 30 minutes, and more

Currently, I am exploring time functionality within React Native by utilizing DayJs. I have noticed a slight inconsistency when comparing 2 different points in time to calculate the time difference. Typically, everything works smoothly such as with 10:00 ...

issue with angular directive not properly binding data

I am curious about the following code: HTML: <div class="overflow-hidden ag-center" world-data info="target"></div> js: .directive('worldData', ['$interval', function($interval) { return { scope: { ...

Tips for attaching functions to a fresh SVG element with jQuery?

My jQuery code creates an <svg> element and appends it to a <div>. When I try to access the appended <svg> using each() after the append() function, the event handler doesn't work. However, if I create the <svg> element before ...

Filling in a text field with the text content (rather than the value) from a dropdown menu

Presently, I have the select box with the id "title" populating a text field with the id "costcenter". The current code works perfectly fine when using the VALUE of the select box to trigger the population of the cost center field. However, my requirement ...

Instructions on generating a fresh Ethereum or Solidity contract for every test using JavaScript and Truffle

overview After developing an Ethereum smart contract using the Solidity language, I utilized Ganache to deploy my contract for testing purposes. However, in order to conduct tests effectively, I need to create a new instance of my contract using JavaScrip ...

Ways to identify which arrays within an object contain an element

This question is unique as it pertains to objects of arrays rather than arrays of objects. I am working with a data structure like the one below and my goal is to determine if any of the arrays inside the object have values. What I'm looking for is a ...

Building a solid foundation for your project with Node.js and RESTful

I need to integrate a legacy system that offers an api with rest/json queries in Delphi. I plan to consume this data and build an app using angular + nodejs. My goal is for my application (client) to only communicate with my web-server on nodejs, which wil ...

"Troubleshooting AngularJS UI Bootstrap Typeahead: How to Fix the Issue

Here is my HTML code snippet: <p> <input type="text" ng-model="destination" placeholder="Destination" uib-typeahead="dest as dest.name for dest in fetchDestinations($viewValue)" typeahead-loading="loadingDestinations" typeahea ...

Encountering an issue with re-rendering components in REACT when using the setState hook

Is there a way to efficiently change the inline style property of multiple items based on their position info stored in a useState hook? I want to update the CSS value of all items except for the one that was clicked on. I tried using setState to achieve t ...

What's the best way to pass parameters through Higher-Order Components in React?

my custom component App import React, { Component } from "react"; import City from "./City"; import withDataLoader from "./withDataLoader"; const MyApp = () => { const MyCity = withDataLoader( City, "https://5e5cf5eb97d2ea0014796f01.mockapi ...