Utilize vanilla JavaScript to invoke the Angular factory

Struggling to find the right title for this query, I'm diving into Angular and using ngMaterial. Currently, I have a toast set up through an Angular factory.

app.factory('notify', ['$mdToast', '$animate', function($mdToast, $animate) {
    return {
        showToast: function(msg) {
             var toast = $mdToast.simple()
                  .content(msg)
                  .action('Close')
                  .highlightAction(false)
                  .position('top right');
            $mdToast.show(toast).then(function() {
              //
            });
        }
    }
}]);

Everything works smoothly when there's a button on the page triggering the toast. But now I also have socket.io running with node monitoring redis for updates to display notifications. The challenge is integrating the factory to show the toast in this scenario.

socket.on('notification.new', function (data) {        
    //call factory here to show toast
    console.log(data);
});

I understand that if it was within a controller, I could simply use:

angular.element().scope().showToast(data)

However, I want to avoid creating an element solely for housing the controller to call the function.

Answer №1

To resolve the issue at hand, I implemented a solution by connecting one of the controller's functions to the window object. Here is an example:

window.showToast = function(msg) {
             var toast = $mdToast.simple()
                  .content(msg)
                  .action('Close')
                  .highlightAction(false)
                  .position('top right');
            $mdToast.show(toast).then(function() {
              //
            });

Subsequently, within the socket io listener (or any plain JavaScript code), I did the following:

socket.on('notification.new', function (data) {        
    //call factory here to show toast
    window.showToast(data); //or however you'd like
});

My approach may not be ideal, but in the absence of any other solutions provided for this question, I decided to share this workaround that at least gets the job done.

Answer №2

To utilize Angular in pure Javascript, you must acquire Angular services.

For more information, check out Call Angular JS from legacy code

  • Use angular.element(domElement).scope() to access the current scope of the element
  • Use angular.element(domElement).injector() to retrieve the current app injector
  • Use angular.element(domElement).controller() to obtain the ng-controller instance.

In your situation, employ the injector service to grab your factory.

Update 1

$injector reference

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

When the MATERIAL UI MENU ITEM is clicked, an action is triggered automatically upon loading the

I added an onClick event listener to a Menu Item in material UI, MUI. Upon loading the page, the onclick function triggers automatically. How can I resolve this issue? const [anchorEl, setAnchorEl] = useState(null) const open = Boolean(anchorEl) const ...

Express server unable to process Fetch POST request body

I'm currently developing a React app and I've configured a basic Express API to store user details in the database app.post("/register", jsonParser, (req, res) => { console.log("body is ", req.body); let { usern ...

Issue with Google Maps Angular directive failing to function correctly

Trying to implement the Google Maps for AngularJS directive within a function has been a challenge. I've managed to make it work by moving $scope.map outside the function call and setting the lat/lon statically. However, my goal is to dynamically set ...

The presence of 'touched' within Angular validation is causing a delay in method execution

Upon utilizing this validation method, it became apparent: <label>Password</label> <input type="password" formControlName="password" class="form-control" [ngClass]="{ 'is-invalid': f.password.touc ...

What is the best way to merge different Vue JS instances (each linked to different html divs) into one cohesive unit using Vue

Essentially, I have a scenario where I've created two HTML divs named vueapp1 and vueapp2. Both of these divs serve the same purpose of displaying information and are linked to their individual Vue instances for extracting JSON data and presenting it. ...

Invoke an Angular service from a separate JavaScript file

I have a few javascript and html files: User.js, index.html, Door.js I am looking to utilize a function in the User.js file. Link to my user.js file Link to my door.js file I am trying to call the getUserInfo function from User.Js within the Door.j ...

Choose a name to show when adding a new user in Firebase

Implementing authentication in my React app using Firebase has been successful for signing up and logging in. However, I have been facing challenges trying to include additional information during the sign-up process. I explored solutions provided on Stack ...

The endpoint 'pusher/auth' returned a 404 error code indicating that it was

I'm currently setting up a private channel using Pusher on a local node.js server. Strangely, I'm encountering a 404 error with my auth endpoint. Initially, I suspected a problem with how I defined the endpoint in relation to the local server&ap ...

Tips for avoiding the babel/cli accessibility issue during Google Cloud deployment

I've encountered an issue while attempting to deploy my modularized Node.js Google cloud function to Google Cloud Platform. The function works smoothly on my local machine, but I'm getting an error during deployment that reads: ERROR: (gcloud.fu ...

Retrieve the initial link value in jQuery and make changes to it

Is there a way in jQuery to append to the current value of an attribute without storing it in a variable first? For example: $(document).ready(function() { $("#btn").click(function() { // get the link currently var linkCurrent = $("#link").att ...

Is there a way to disable page prefetching for Next.js Link when hovering over it?

Whenever a link is hovered over in my production application, an XHR request is sent to the server. I need to find a way to prevent this from happening. I tried using prefetch={false} but it didn't work. Any suggestions on how to resolve this issue? ...

What is the process for updating the label name when a file is chosen?

Check out this HTML code snippet: <input type="file" class="custom-file-input" accept="image/*" onchange="loadFile(event)" id="customFile"> <label class="custom-file-label" id="chan ...

Delete an entry in a singular mapping in a one-to-one connection [TypeORM]

Is there a way to remove an index from a one-to-one relationship in TypeORM? @OneToOne(() => Customer, { cascade: true }) @JoinColumn({ name: 'customer', referencedColumnName: 'uid' }) customer: Customer I searched the d ...

Is my Bootstrap malfunctioning? The grid system seems to be malfunctioning

My very first question here is quite simple. I have a script that creates rows with dynamic content by appending 4 boxes (columns) in one row and then appending the row to the container. After completing this process, it appends the container to the main c ...

Can you explain the steps to implement this feature in a modal window using jQuery?

My HTML list contains a bunch of li elements. ul li img .det li I am looking to create a modal popup that appears when I click on something. I want this modal popup to have previous and next buttons, preferably implemented using jQuery. I have alr ...

Error message: Nextjs encounters hydration issue only in the production environment

I've been facing this issue for hours now. I deployed my Next.js application on Vercel and encountered numerous hydration errors there. Interestingly, in my local development environment, I don't experience any errors at all. I came across sugge ...

Modifying the Resources in FullCalendar

I am currently working on creating a web calendar that offers multiple viewing options. I have separate views for Students and Projects (both displayed as timeline views in FullCalendar, with Students and Projects acting as resources). My main issue is fi ...

Is it possible to generate unique identifiers for v-for keys using vue-uuid?

I'm attempting to utilize a random string (UUID v4) using vue-uuid for existing items and future additions to the list in my to-do list style application. However, I'm uncertain about the correct syntax to use. After installation, I included it ...

Can we include intricate items within a redux store?

As I delve into developing a React application with Redux, I encountered an unexpected scenario. At one point, we inserted a DOM element within the store, causing issues with the Redux extension that freezes when the action is triggered. Despite this compl ...

Next.js is failing to infer types from getServerSideProps to NextPage

It seems like the data type specified in getServerSideProps is not being correctly passed to the page. Here is the defined model: export type TypeUser = { _id?: Types.ObjectId; name: string; email: string; image: string; emailVerified: null; p ...