AngularJS - $scope.$destroy does not eliminate listeners

I am currently exploring how to develop my own "one-time binding" functionality for AngularJS version 1.2 and earlier. I came across this response which explains the process of creating a custom bindOnce directive. Upon using the provided directive:

    app.directive('bindOnce', function() {
    return {
            scope: true,
            link: function( $scope ) {
                setTimeout(function() {
                    $scope.$destroy();
                }, 0);
            }
        }
    });

The data is bound only once. However, I noticed that even though the data is bound once, the $$watchers are still active. You can verify this by checking the watcher count in the following JSBin example - running the commented watcher count code in the console displays that the watchers are still present.

UPDATE: Interestingly, when utilizing the same directive with Angular 1.3, the watcher count actually becomes 0!!!

Answer №1

Utilize the cleanup method to eliminate watchers:

function cleanup(element) 
  { 
  element.off().removeData();

  var injector = currentSpec.$injector;

  element.$injector = null;

  // clearing jQuery's fragment cache
  angular.forEach(angular.element.fragments, function(val, key) {
    delete angular.element.fragments[key];
  });

  angular.forEach(angular.callbacks, function(val, key) 
    {
    delete angular.callbacks[key];
    });

  angular.callbacks.counter = 0;
  }

Implement a self-destructing service as a one-time binding solution:

function onetime()
  {
  /*...*/
  onetime = Function;
  }

angular.module('myApp').constant('bindonce', onetime);

angular.module('myApp').controller('foo', function($bindonce){
  this.$inject = '$bindonce';
  $scope.mybind = $bindonce();
} 

Consult the migration guide for insight into any disruptive changes:

Resources

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

Transforming a simple MySQL query into a structured nested JSON format

Is there a way to easily reorganize data without using complex for loops (perhaps with Underscore.js or refining the MySQL query)? I have data formatted like this: [ { "J_NUM": "BOAK-1212", "X_DUE_DATE": "2012-06-20T00:00:00.000Z", "X_LEAD_T ...

Flick user media cards left or right to uncover the following one

I am currently working on creating a widget that will display user media objects in a horizontal layout using ng-repeat. The goal is to allow users to swipe left or right to reveal the next media card, similar to the image shown below. In the example, you ...

Here is a unique version of the text: "Implementing a JavaScript function in Angular to activate the data-bs

Attempting to use JavaScript in angular to close/hide a bootstrap5 modal, encountering an issue where the hide function in bootstrap is not working. When manually clicking a button with data-bs-dismiss attribute, it closes the modal as expected, but when t ...

Problems with Navbar rendering on multiple occasions

GENERAL INFO I've encountered an issue with the re-rendering of my sidemenu in Gatsby. Despite my efforts, I can't prevent the sidemenu from re-rendering and overriding the data that I set for it. const [activeParent, setActiveParent] = useState ...

Error message: Unchecked runtime error - Unable to retrieve data from the specified URL. The extension manifest must include permission to access this particular host. This issue is occurring in manifest

Can someone help me out? I keep on receiving the error messages Unchecked runtime.lastError: Cannot access contents of url. Extension manifest must request permission to access this host. and Unchecked runtime.lastError: Could not establish connection. Rec ...

What steps should I take to address a situation in which a Protractor test becomes stuck indefinitely?

I've encountered an issue with a test case that was previously running successfully but is now getting stuck indefinitely during execution. This problem occurs each time the test attempts to click on a specific element, causing the test to hang withou ...

transfer jquery element using jquery ajax

How can I send a jQuery object to a PHP function using POST? When I stringify the object, I get the following output: [ { "id": "701", "user_id": "2", "playlist": "ukg%20garage", "tracks": "5", "thumbnail": "Coldplay.jpeg", "crea ...

Running asynchronous calls in node.js using express

In my code, there are two functions. The first one: router.post('/getStances', function(req, res, next) { var data = '{"success":"0"}'; data = queries.getStances(req.body.issues[0], req.body.issues[1], req.body.issues[2], req.b ...

Retrieve the IDs of list elements in order to dynamically update a div using AJAX

I'm facing a bit of a challenge at the moment. I have a webpage that uses jQuery to load three different views: one displaying all categories associated with the user, another showing the image and name of items within the selected category, and a thi ...

Having trouble with implementing ng-hide and ng-show functionality

I have been working on creating my very first Angular website and so far, everything has been going smoothly with the first page. However, I am facing an issue with the second page not appearing as expected when it meets the condition set with ng-show in t ...

Is it possible to implement hierarchical validation within reactflow nodes?

I am currently utilizing reactflow to establish a network of sequences, each possessing their own unique "levels." My primary objective is to restrict connections between sequences based on their respective levels. For instance, a level 5 sequence should ...

Wait to display the page until receiving a response from the $http.get request

Currently, I am incorporating AngularJS in my website. However, when running it on my local server, it requires data from a remote server through the '$http.get' method, resulting in a delay of 3-4 seconds. This leads to an unattractive appearanc ...

Steps for programmatically closing a Dialog Window in a showmodeldialog window

When opening the window, I follow this approach: var MyArgs = new Array(ParmA, ParmB, ParmC, ParmD, ParmE, ParmF); var leftpost = getWindow_TotalWidth() - 1000 - 100; var WinSettings1 = "dialogHeight:580px; dialogWidth:950px;edge:Raised; center:Yes; resi ...

Guide to Implementing i18n-iso-countries Library in React

I am currently developing a React application and attempting to utilize the i18n-iso-countries package to retrieve a countries object in English where keys represent iso codes and values represent country names. This process is straightforward in Node.js, ...

Is there a way to halt or end an interval within a function triggered by useEffect()?

I am currently working on a countdown timer script using react.js. The timer displays a 3 or 5 seconds countdown before starting, with data for these countdowns coming from another component. I am facing an issue with controlling the main countdown timer ...

The Javascript functionality does not seem to be functioning properly within the Bootstrap navigation

I'm having an issue with my Bootstrap navbar JavaScript. Below is the code that's causing the problem: <script type="text/javascript"> $(".nav a").on("click", function () { $(".nav").find(".active").removeClass("active"); $(this).p ...

Retrieve data from a text file using ajax and then return the string to an HTML document

Just starting out with ajax, I have a text file containing number values For example, in ids.txt, 12345 maps to 54321 12345,54321 23456,65432 34567,76543 45678,87654 56789,98765 Here is the Html code snippet I am using <html><body> < ...

NodeJS API integration failure during ReactJs login attempt

Currently, I am tackling a small project on implementing user login functionality in ReactJs with Nodejs and Express-session. The issue I am facing is that my front end (React login page) isn't functioning properly. Below is the Fetch API code snippet ...

Utilizing ng-change in an AngularJS directive with isolated scope to transition towards a component-based architecture. Let's evolve our approach

I've been struggling to get ng-change to trigger in my directive with an isolated scope. I'm working on transitioning from ng-controller to a more component-based architecture, but it's turning out to be more difficult than I anticipated. I ...

Eliminating unnecessary gaps caused by CSS float properties

I need help figuring out how to eliminate the extra space above 'Smart Filter' in the div id='container_sidebar'. You can view an example of this issue on fiddle http://jsfiddle.net/XHPtc/ It seems that if I remove the float: right pro ...