Leveraging a service method declared within a module pattern in a different context

I have a custom Angular service that looks like this:

videoApp.factory('cacheLoader', function ($http, $filter, $rootScope) {
    this.self = this;
    return {
        load: function (url, allowCache) {
            if(allowCache == false || localStorage.getItem(url) && (parseInt(localStorage.getItem(url + 'time')) + 20000) < (new Date().getTime()) || (!localStorage.getItem(url) )) {
                $http.get(url).success(function (data) {

                    $rootScope.allData = data;
                    $rootScope.videos = data;

                    $rootScope.categories = $filter('categoryFilter')(data);

                    if(allowCache == true && parseInt(localStorage.getItem(url + 'time')) + 20000 < (new Date().getTime() )) {
                        localStorage.setItem(url, JSON.stringify(data));
                        localStorage.setItem(url + 'time', new Date().getTime());
                    }

                });
            } else {
                $rootScope.allData = JSON.parse(localStorage.getItem(url));
                $rootScope.videos = JSON.parse(localStorage.getItem(url));
                $rootScope.categories = $filter('categoryFilter')(JSON.parse(localStorage.getItem(url)));
            }
        },
        getFilteredResults: function (category, data, callback) {
            callback = callback || $filter('articleFilter');
            $rootScope.videos = callback(category, data);
            return $rootScope.videos;
        }
    };
});

My current dilemma is trying to call cacheLoader.getFilteredResults inside the cacheLoader.load function. Since it's a window object, I can't directly reference it. I've attempted to bind "this" to the entire module pattern, but encountered an error.

Does anyone know of a way to achieve what I'm attempting to do here?

Answer №1

Utilizing the this.getFilteredResults function within the context of the load method is essential:

videoApp.factory('cacheLoader', function ($http, $filter, $rootScope) {
    this.self = this;
    return {
        load: function () {
            this.getFilteredResults();
        },
        getFilteredResults: function () {
            alert('hello');
        }
    };
});

If there's a necessity to tackle references to this inside a callback, you can implement the following approach:

return {
    load: function () {
        var that = this;
        doSomething().then(function(data) {
            that.getFilteredResults();
        });
    },
    getFilteredResults: function () {
        alert('hello');
    }
};

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

What steps can be taken to ensure that the application loading process is not reliant on web service

I recently developed a PhoneGap application that initiates a web service call upon loading the index.html page. The call is made using the following code: $.ajax({ type: "GET", url: "http://webserviceurl.com/service", cache: false, async: true, ...

What is the best way to show nested labels on separate lines simultaneously?

Despite attempting to utilize the map method as suggested in my research, it appears that it may not be suitable for the structure I am working with: const stepLabels = [ { labels1: ['First One'] }, { labels2: ['Second One', 's ...

Can you point me in the direction of the code for the session.generate() function in Express JS?

Currently, I am delving into the intricacies of session storage and generation within Express JS and Node.js: Store.prototype.regenerate = function(req, fn){ var self = this; this.destroy(req.sessionID, function(err){ self.generate(req); fn(er ...

AngularJS: Move forward with controller execution after completion of a looped service method

Currently, I am implementing a networkService in Angular which is responsible for looping while the internet connection is unavailable. The goal is to resume execution once the connection is restored. Below is an example of a controller: MyApp.controller ...

An issue occurs with the scope of a variable during the compilation of Relay Modern code, resulting in an

I have created the following simple Relay Modern code snippet: import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { QueryRenderer, graphql } from 'react-relay' import environment f ...

The NodeJS and Python-Shell .run function fails to display the standard output

I am currently working with NodeJS and a Python script. To retrieve results from my Python script, I have been using Python-Shell which you can find detailed documentation for at: github.com/extrabacon/python-shell Typically, to get prints from the scrip ...

What is the best way to send an email with a randomly generated HTML output using a <button>?

I am currently working on a feature where a random HTML output is sent to me via email whenever a user clicks on a button on the website page. The user receives a code when they click the button, and I want that code to be emailed to my address automatical ...

Unable to change the filename when utilizing Angular.js ng-file-upload

After uploading a file using Angular.js ng-file-upload, I am attempting to rename the file. However, when I remove the properties ngf-min-height="400" ngf-resize="{width: 400, height:400}", I encounter an issue. Below is my code: <input type="file" dat ...

The communication between socket.io encountered a net::ERR_SSL_PROTOCOL_ERROR

Here is the client code I am using: const socket = io(url); And this is the server code running on a Linux server with Express: const server = require("http").createServer(app); However, when I attempt to establish a connection, an error occurs. https:/ ...

Unable to retrieve HTTP call response during debugging, although it is visible in the browser

When I send an HTTP request to create a record, I am able to see the added record id in the Network section of browsers like Chrome and Firefox. However, when I try to debug the code and retrieve the same id value, I encounter difficulties. I have tried us ...

Error: The function props.addToCart is not accessible

While attempting to trigger my action on the client's click of the "addToCart" button to add a new product to the cart, I encountered the error message: "TypeError: props.addToCart is not a function." I am relatively new to Redux and have grasped the ...

Retrieving the data from an AJAX JSON variable

Inside my JavaScript function, I am fetching data like this: var jsonData = $.ajax({ url: "pie_chart_community.php", community_id: $c_id, dataType: "json", async: false }).responseText; Is there a way for me to access the community_id in ...

concealing the date selection feature on the data picker

$('.year').datepicker({ changeMonth: true, changeYear: true, showButtonPanel: true, dateFormat: 'MM yy', onOpen: function(dateText, inst) { $("table.ui-datepicker-calendar").addClass('hide') }, onClos ...

Can one echo the value of a variable within an array reference?

I am trying to extract the value of an input based on its class and then use that value in an associative array Here is my current javascript code: var phone_code = document.getElementsByClassName( 'model' ).value; var phone = []; phone["6s"] = ...

Adding items dynamically to a React-Bootstrap accordion component can enhance the user experience and provide a

I am retrieving data from a database and I want to categorize them based on "item_category" and display them in a react-bootstrap accordion. Currently, my code looks like this: <Accordion> { items.map((item, index) => ...

Unable to make a div grow within a Popper component in a React.js application

I'm facing a challenge with implementing a CSS feature and need some assistance. https://i.stack.imgur.com/KXpGd.png Upon clicking the "See link options" button, the content loads but spills out of the popper. My goal is to have the popper expand in ...

What is the best way to incorporate images from an external module into my React project?

Is there a way to include images from an external module (npm install external-module) in my project's public assets? The images are located in the directory path myProject/node_modules/external-module/dist/img. ...

Is there a way to make a text area box visible using JavaScript?

Currently, I am developing an automation script in Python using Selenium. My objective is to make a textarea box visible, as I need to insert some arguments into it. Here is the code snippet that I am utilizing: element = driver.find_element_by_id('g ...

Using JavaScript, transform a client's date/time string into a JSON-compatible date/time string

I need to find a way to convert a client's date/time string on a form into a JSON date/time string using JavaScript with moment.js for a Django REST API backend service. Here is the initial attempt: document.getElementById("dt_tm").value = moment(do ...

The ng-click function in Angular 1.2 seems to be malfunctioning

Here is the code I am currently working with: var tr = $event.currentTarget; var el = angular.element("<tr class='detailed-document'><td colspan='3' ng-click='alert();'>Hello</td></tr>"); v ...