Resolved issue with $watch repeatedly triggering due to missing ng-hide functionality

I am facing a scenario where I am fetching JSON data from a backend and then rendering it using a template that contains several ng-show directives.

<div>
    <span ng-show="config.displayMode == 'A'" class="ng-binding">${A}</span>
    <span ng-show="config.displayMode == 'B'" class="ng-binding">${B}</span>
    <span ng-show="config.displayMode == 'C'" class="ng-binding">${C}</span>
</div>

Upon receiving new data, the template removes the existing elements and renders new ones.

Although this process works correctly and efficiently, I have observed through the Batarang performance tool that watches are being leaked every time elements are removed. As this page remains open for extended periods, the memory usage and digest time gradually increase, which is something I want to prevent.

EDIT The elements are removed using the .empty() function of jQuery.

As requested, I have created a plunkr. The example is simple, adding an element with an ng-show every time something is typed in a box. If the box is cleared, the ng-show elements are deleted. By using Batarang, you can see that watches persist on the performance tab.

MY Question How can I clear the watches created by an ng-show directive?

Answer №1

If I interpret your message correctly, implementing this solution may resolve your issue:

app.directive('myDirective', function($compile) {
  return {
    restrict: 'A',
    scope: {
      myDirective: '='  
    },
    link: function($scope, elem, attr, ctrl) {
      $scope.$watch('myDirective', function(){
        if($scope.myDirective.length > 5){
          elem.append("<div class='second'>Length is greater than 5</div>")
        } else {
          elem.empty();
        }
      });
    }
  };
});

The issue in your code is that you are not actually removing the elements from the DOM. Instead, you are simply hiding them, causing the watchers to remain active. Refer to this Plunker for implementation.


Here is a screenshot illustrating the elements that will not be correctly removed with your current code:

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

Removing an element from an array by evaluating each item within the array

Input array: ["temp/1/Lounge/empty", "temp/1/Lounge/66,66,66,66,66,66,66,66,64,64,64,64…,64,64,64,64,64,64,64", "temp/2/Lounge/empty", "temp/3/Lounge/empty"] I have a list of elements like the above. Each element consists of four parts separated by s ...

Storing user information in Angular after login and implementing JWT authentication

Is it advisable to save any user information other than JWT in local storage or cookies after a successful login? (The user profile object is already saved and encrypted in the JWT payload sub-part.) I need the user profile object ready before initializing ...

What is the best way to merge two fetch requests in order to gather the required data?

If I want to create a website with details about movies, one crucial aspect is getting information on genres. However, there's a challenge in the main data request where genres are represented by IDs. I need to execute another query that includes thes ...

Can you explain the significance of npm WARN excluding symbolic link?

Could you please explain the meaning of npm WARN excluding symbolic link? Also, any advice on how to resolve this issue? ...

The value stored in $_POST['valuename'] is not being retrieved

Having recently delved into ajax, I am encountering some difficulties in making it function properly. The objective of the code is to send two variables from JavaScript to PHP and then simply echo them back as a string. However, instead of receiving the e ...

Make sure a div is displayed on top of any content currently in fullscreen mode

I recently encountered an issue with my Chrome extension where a menu I inserted into the page would disappear whenever a flash or html5 video player went full screen. Is it possible to have two objects in full screen simultaneously, or is there another so ...

Navigating the Angular (ng-Grid) testing waters: emitting an event with data using Jasmine

Assuming I have the following listener: $scope.$on('ngGridEventEndCellEdit', function(event, data){ var entity; if(data && data.targetScope && data.targetScope.row) { entity = data.targetScope.row.entity; } else { entity = event.t ...

Updating cannot be done while rendering, within the onError function of the Image

I recently encountered a warning stating that I cannot update during render. The recommendation was to update in ComponentWillMount. However, since I need to change the state after checking if the image is in an Error (not Loaded) state, I must make the ...

Struggling to make React respond to button clicks without resorting to using addEventListener

Can anyone help me figure out why I can't get the onclick handler to execute in reactjs when specifying it inline for a button? The only solution that worked for me was using addEventListener. From what I understand, this code should work: <button ...

Is it possible to interact with Java SE jars using JavaScript?

I need to integrate an API that is written in Java with a Client written in JavaScript. Is there any way to use this API, possibly along with other Java-SE JARs, in Webstorm? Any assistance would be greatly appreciated. Thank you! ...

What is the method for getting js_xlsx to include all empty headers while saving the file?

In the midst of developing a Meteor App, I've incorporated the Node.js package known as "js_xlsx" from "SheetJS", produced by "SheetJSDev". This tool enables me to convert an Excel sheet uploaded into JSON on the backend. The intention is to store thi ...

Assessing the validity of a boolean condition as either true or false while iterating through a for loop

I am facing an issue that involves converting a boolean value to true or false if a string contains the word "unlimited". Additionally, I am adding a subscription to a set of values and need to use *NgIf to control page rendering based on this boolean. &l ...

Images not showing in Vue.js

I have been working on setting up a carousel using bootstrap-vue. It is being generated dynamically through an array containing three objects with keys such as id, caption, text, and image path. The issue I am facing now is that while the caption and text ...

What is the best way to access a variable from one JavaScript file in a different file?

Currently, I have a simple cube scene set up in Three.js Now, my goal is to add camera movement using perlin noise. To achieve this, I found and incorporated the Perlin noise library into my project: https://github.com/josephg/noisejs I then included th ...

Automated tool for generating random JSON objects

Looking for a tool that can generate random JSON objects? I'm in need of one to test my HTTP POST requests and incorporate the random JSON object into them. Any recommendations? ...

Prevent zooming or controlling the lens in UIWebview while still allowing user selection

Is there a way to disable the zoom/lens on uiwebview without affecting user selection? I'm trying to avoid using "-webkit-user-select:none" in my css. -webkit-user-select:none ...

Using the length of an array as an iterator within a nested ngFor loop in Angular 9

I am looping through an array of objects where each object contains another array of objects with attributes like "name" and "id". The length of this array of objects (noticias) varies. I am struggling to display these values and have only managed to acce ...

Is there a method in Angular JS to monitor modifications in the DOM that doesn't involve using scope.watch?

I'm working on creating an angularjs bootstrap accordion that automatically scrolls to the top when opened. While I found some solutions that are similar to what I want: AngularJS / ui-bootstrap accordion - scroll to top of active (open) accordion ...

Tips for improving communication between sibling directives in AngularJS applications

All: Imagine I have two directives (dir1 and dir2), both with isolated scopes. After reading some posts, I understand that I need to use "require" to access the scope of the other directive, but one question continues to perplex me: If I use ng-repeat to ...

Maintaining a JavaScript script within the local project directory and integrating it for use with Angular

I could use some assistance. I am currently working on an Angular project and making API calls (GET/PUT) to a remote server. In order to improve the performance of my application, I decided to store the necessary JS file locally in the assets folder. Init ...