Prevent event listeners from being triggered during the '$destroy' event. Error: $on function is undefined

As I attempt to halt all event listeners when the scope is destroyed, a certain error arises.

The following error is displayed:

TypeError: vm.$on is not a function; 

Even using vm.on(..) does not resolve the issue

    angular.module('app.layout')
      .controller('DashboardController', DashboardController);

      DashboardController.$inject = ['$interval','dataservice'];


      function DashboardController($interval, dataservice) {
        var vm = this;
        vm.name = "DashboardController";


        console.log('Init Dashboard Controller');
        initEvents();
/*
 ...
*/

    /////////////////////////////

    function initEvents() {
          vm.$on('$destroy', function() {
            vm.stop();
            console.log('DashboardController scope destroyed.');
          })
        }

Answer №1

The issue here is that the variable vm does not have the $on(... method declared within it. You should instead use $scope. Inject it into your controller and declare it as $scope.$on.

When utilizing the controllerAs syntax, it is commonly misunderstood that you should not use $scope at all. However, the recommendation is to avoid using $scope for certain tasks rather than completely eliminating it from your controller. The scope will always exist as an internal part of your controller; just refrain from using it as a view model. Nevertheless, you can still use it for activities like listening to events, broadcasting, emitting, etc.

Consider trying something along these lines (after injecting $scope into your dependencies):

$scope.$on('$destroy', function() {
    vm.stop();
    console.log('DashboardController scope destroyed.');
})

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

Merging Two Angular Pages within a Jhipster Application

My jhipster application is simple, generating 2 entities: Product and Category. The generated pages to list the data for these entities can be found here. Specifically, there are pages for Product and Category. If I want to create a new page that combines ...

Using jQuery DataTable to fetch JSON data upon Document Loaded

I am struggling to implement a PHP script that returns JSON data to populate a DataTable. The PHP script 'api/exceptions_all.php' is as follows: <?php $select = "SELECT '', [FOR_PARTNER], [FOR_NAME] FROM [brokerage].[dbo].[for_ex ...

Challenges with using the $filter('limitTo') function in AngularJS

Struggling with implementing the limitTo filter in JavaScript The angularjs docs for limitTo explain that the filter should be used as follows: $filter('limitTo')(input, limit, begin) It's important to note that the begin parameter is opt ...

Jerky visuals on the canvas

My canvas animation runs smoothly in Chrome, but it's as choppy as a bad haircut in Firefox. Surprisingly, the code is not even that complex. Is there anything in my code that could be causing this slowdown? Here is the jsfiddle link for reference: h ...

What is the best way to target changing elements displayed by *ngIf?

Trying to access a dynamic element generated by ngIf in the code below has proven to be challenging. I attempted two different methods: Using ElementRef and querySelector Component template: `<div class="test" *ngIf="expr"> <a id="b ...

What steps should be followed to create an npm script that can execute multiple commands for running test cases?

When running the end-to-end (e2e) tests for my AngularJS application, I find myself having to execute a series of commands in separate shell sessions: // start the selenium server webdriver-manager start // initialize a http server to host the current fi ...

In my attempt to simulate redis using jest and javascript, I've noticed that whenever I try to access redis.mock.instance[0], it consistently returns as empty

I'm currently attempting to simulate redis with jest and JavaScript, but I'm encountering an issue where accessing redis.mock.instance[0] always returns empty. RedisWrapper.js: const Redis = require('ioredis'); const REDIS_USER_TTL = 6 ...

Why does my Visual Studio Code always display "building" when I launch an extension?

https://code.visualstudio.com/api/get-started/your-first-extension I followed a tutorial to create a hello world extension. Why does my VSCode always display 'building' when I run the extension? Executing task: npm run watch < [email p ...

A JavaScript function that is only triggered half of the time

After browsing through various forums like StackOverflow, I couldn't find a solution that perfectly fits my issue. I may be new to programming, but I've managed to create several projects already. Currently, I am working on integrating them into ...

Changing the width of the initial column in a Bootstrap grid while using ng-repeat in Angular

Is it possible to double the width of the first column using AngularJS (from col-xx-4 to col-xx-8)? In Bootstrap, this task is straightforward (as shown in Section B of the attached plunker). I attempted to achieve the same result in Section A with the h ...

Monitoring the usage of a specific component's screen time in a React Application

Is it possible to accurately track the time a specific component is rendered with certain props and while being on an active screen in React? I've had trouble finding a suitable library for this task. What would be the most effective approach to tackl ...

Ways to retrieve data from an AJAX success callback function

Within my front end JavaScript application, I need to execute an ajax request in order to retrieve data from the server. Once this data is acquired, I aim to display it within the view. var retrievedData; $.ajax({ url:"/getDataFromServer.json", ty ...

How to retrieve attributes of a model from a related model in Sails.js

Currently, I am utilizing the beta version(v0.10.0-rc3) of Sails.js and have updated the database adapter to PostgreSQL in order to enable associations via the Waterline ORM. My main focus is on creating a role-based user model for authorization based on d ...

Troubleshooting issue with Django forms and JavaScript interactions

For the past day, I've been grappling with a particular issue and haven't made much progress. My setup involves using a django inline form-set, which displays all previously saved forms along with an additional empty form. To show or hide these f ...

Discover the method for tracking idle time with jQuery and PHP

I have a script that utilizes PHP sessions through a custom class. One of the methods in this class calculates the remaining seconds before the session expires. Whenever the user refreshes the page or opens a new one, the idle time counter is reset using ...

Error message in JS and HTML is totally bizarre

My expertise in JavaScript is very limited, so the terms I use might not be entirely accurate. However, I'll do my best to explain the issue at hand. I'm facing a peculiar problem... I've been attempting to modify someone else's JS scr ...

Analyzing User Input and Database Information with Mongodb

Here's the HTML form I'm working with: <form id="contact-form" method="POST" action="/search"> <label for="company">Phone company</label> <input type="text" name="company" value=""> &l ...

The type 'string | undefined' cannot be assigned to type 'string'

I am facing a challenge in comparing two arrays, where one array is sourced from a third-party AWS service and its existence cannot be guaranteed. Despite my efforts to handle potential errors by incorporating return statements in my function calls, I con ...

The failure of the Selenium script can be attributed to the presence of the AJAX

Struggling to automate an application with an AJAX loader causing issues? Getting the dreaded error message about element not being clickable when the loader is active? Frustrating, right? But fear not! I have devised a clever solution in the form of a wr ...

Is it possible to receive real-time updates for a specific location in Cesium

I am currently developing a live tracking application using Cesium, and I'm encountering an issue with updating the point location on the map in real-time. Currently, my Cesium viewer successfully receives the data from the server in JSON format and ...