Listening for events with $rootScope.$on inside a service or factory

I'm encountering a peculiar issue with the $rootScope.$on method within a service or Factory.

Here's an example of the service:

app.service('testService', function($rootScope){

this.var1 = 5;

this.change = function(n){
    this.var1 = n;
}

$rootScope.$on('service', function(event, n){
    //this.var1 = n;
    console.log(this.var1);

});
});

The problem lies in the fact that it should display 5 in the console. However, I am unable to access the service's variables within the $rootScope.$on method...

Below is the corresponding controller:

app.controller( 'HelloCtrl', function($scope, testService, testFactory, $rootScope)
{
$scope.fromService = testService;

$rootScope.$broadcast("service", 12);
});

Here is the link to the JSFiddle showcasing the issue: jsFiddle

What could be the root cause of this problem?

Any suggestions on how to resolve this issue?

Answer №1

It is necessary to assign this to a new variable in order to create closure.

In the callback function, this refers to something else...

Here is an example that may assist you:

//example demonstrating difference between factory and service in angular.js
var app = angular.module('myApp', []);

app.service('testService', function($rootScope){

    var testService = this;

    this.var1 = 5;

    this.change = function(n){
        this.var1 = n;
    }

    $rootScope.$on('service', function(event, n){
        //this.var1 = n;
        console.log(testService.var1);

    });
});

app.controller( 'HelloCtrl', function($scope, testService, $rootScope)
{
    $scope.fromService = testService;

    $rootScope.$broadcast("service", 12);
});

http://jsfiddle.net/mc4ow2b6/4/

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

Locate the nested route within one of the child components in React Router that corresponds to a specific id

Picture this scenario where I have a list of routes: const routes = [{ id: "1", path: "animals", children: [{ id: "1.1", path: "birds", children: [{ id: "1.1.1", path: "co ...

Within Angular2 NGmodule, I aim to dynamically load two distinct sets of route modules depending on certain conditions

In Angular2, I am looking to load two different sets of route modules - one for jobseekers and the other for employers. Both sets will have the same URLs but will contain different modules for jobseekers and employers. Therefore, I need a way to dynamicall ...

Integrating draw2d into Mean.js: A Step-by-Step Guide

I'm new to the MEAN Stack and I'm having trouble with something that seems pretty basic. My issue is trying to inject a new instance of draw2d from their downloadable library. The error message I keep receiving is: "Uncaught Error: [$injector: ...

"MongoDB Aggregating Data with Nested Lookup and Grouping

I have 3 collections named User, Dispensary, and City. My desired result structure is as follows: { _id: , email: , birthdate: , type: , dispensary: { _id: , schedule: , name: , address: , phone: , u ...

AngularJS - Highlighted row value

Here is a helpful example you can refer to: Check out the demo here: The code provided works well, but I would like to add a button. When this button is clicked, an alert should display the value of the name column - for example, "Noodles". This snippet ...

Manually setting focus to input text in AngularJS: How it's done

I am having difficulty manually setting the focus on an input element using $event.currentTarget.focus();. Despite following the correct syntax, it seems to not be functioning as intended. Below is a snippet of what I am trying to accomplish: HTML: <d ...

Node.js and the Eternal Duo: Forever and Forever-Montior

Currently, I am utilizing forever-monitor to launch a basic HTTP Node Server. However, upon executing the JavaScript code that triggers the forever-monitor scripts, they do not run in the background. As a result, when I end the TTY session, the HTTP server ...

Event cancellation for AngularJS UI-Grid filters

Hey there, I'm currently working with the Angular UI grid and have implemented filters and grouping in the grid. By default, I am expanding all rows using the following code snippet: $scope.expandAll = function(){ $scope.gridApi.treeBase.expandAl ...

What is the best way to anchor the components to a specific location on the screen in ASP.NET?

Currently I am working on creating a registration page in asp.net. I have been using panels to group the components such as labels, dropdown lists, and text boxes. However, when I run the page, I noticed that the positions of these components keep changing ...

What is the proper way to handle postMessage events from a Streamlit iframe within a Next.js app?

I'm currently in the process of integrating a Streamlit app into a Next.js application by embedding the Streamlit within an iframe. My main goal is to send data from the Streamlit app to the Next.js parent using window.postMessage, specifically focusi ...

What causes data to update in a Vue template but not in the JavaScript portion of the code?

The topic in the template section updates when its value in the parent component changes, however, the same value in the script part remains the initial value it received at search_params.set('param1', this.topic);. Everything else in the code is ...

Perform time update every second

Is it feasible to have my timeupdate function run every second? (Using VUE CLI) @timeupdate="videoSecond" videoSecond(){ let Second = this.player.currentTime(); let CaptureList = this.capturesList; CaptureList.forEach(element => ...

Implement a hover effect on a specific class targeting a nested element using JavaScript

Is there a method to apply a class that modifies rules for a child element using Javascript? I have successfully added it with CSS but am struggling to do the same with Javascript. Removing the class in JS is easy by referencing the classname before the ho ...

What is preventing the buttons from filling the entire space of the parent element in this case?

https://i.stack.imgur.com/kbiWi.png I'm trying to figure out how to make the Repos and Stars buttons fill the entire height of their parent container, similar to the Github icon. Unfortunately, the code below is not achieving this effect. I attempted ...

The Angular bootstrap datepicker does not correctly format the date value stored in the ng-model variable

I am currently utilizing a bootstrap date-picker in my Angular application. However, whenever I select a date from the date-picker, the underlying ng-model that I have bound gets updated. I would like that ng-model to be in the date format 'MM/dd/yyyy ...

Interactive bar chart that updates in real-time using a combination of javascript, html, and

Current Situation: I am currently in the process of iterating through a machine learning model and dynamically updating my "divs" as text labels. My goal is to transform these values into individual bars that visually represent the values instead of just d ...

Removing unnecessary keys from intricate JSON data (with the use of pure JavaScript)

I've experimented with various methods to dynamically parse and remove keys with empty values from a JSON file using JavaScript. Currently, I can successfully delete non-nested keys, except for empty strings that have a length greater than 0. My mai ...

Leverage the power of Bootstrap by incorporating not one, but two carousels on a single page - one featuring a single item per

I have a unique challenge with using multiple Bootstrap Carousels on my WordPress website One of the carousels features one item per slide, while the other carousel has three items per slide, moving one item at a time in a cyclical pattern like this: [1, ...

The onBlur attribute does not seem to be functioning properly under a specific condition

I've been attempting to customize the appearance of a search box using the onFocus and onBlur attributes, but unfortunately I haven't been able to achieve the desired outcome. Below is my HTML code: <form action="index.php" method="post" clas ...

A guide on resolving the 'Unexpected identifier array in JSON Parse Error' encountered during an AJAX Request

I'm currently working on setting up a Contact Form Validation and I require the variable $msg from a php script called 'sendEmail.php'. The actual mailing system is functional, as the script successfully receives form inputs from index.php a ...