How to create a fresh factory instance in Angular Js

I have implemented a factory in my application to retrieve a list of folders and display it on the front end. Additionally, I have a form on the front end where users can add new folders to the existing list. After adding a folder, I need to refresh my factory instance and display the updated list of folders.

// Factory

angular.module('myapp').factory('archiveService', ['$http', 'ApiUrl', function($http, ApiUrl) {
var archiveService = function() {
    this.repos = [];
    this.busy = false;
    this.page = 0;
};
archiveService.prototype.nextPage = function() {
    if (this.busy) return;
    this.busy = true;
    var url = ApiUrl.url + '/folders/?page=' + this.page;
    $http.get(url).then(function(res) {
        console.log(res);
        this.repos = res.data;
        if (items.repos == 0) {
            return;
        }
        this.page += 1
        this.busy = false;
    }.bind(this)).catch(function(data) {
    }.bind(this));
};
return {
    archiveService: archiveService,
}

}]);

// Controller

angular.module('myapp').controller('archiveModalController', ['$rootScope', '$scope','archiveService', function($rootScope, $scope, archiveService) {

// To show new data after update, I need to refresh this

    $scope.archivelist = new archiveService.archiveService();

}])

I am looking for a way to refresh so that I can retrieve the latest data.

$scope.archivelist = new archiveService.archiveService();

Answer №1

Angular services adhere to the singleton pattern, meaning that a class is only instantiated as a single object.

In addition, if you are using a factory:

angular.module('myapp').factory('archiveService', [<dependencies>, function () {
    function nextPage() {
        //code here
    );

    return {
        nextPage: nextPage
    }

}]);

Then in your controller, you can simply do:

archiveService.nextPage();

When looking at the code, it seems like nextPage could accept the page as a parameter and since repos is an array, I assume you meant to add the new data fetched to that array?

Which would be: this.repos.push(res.data) instead of this.repos = res.data;

The important thing is to call the correct service/factory method from the controller whenever you want to request new data.

So, in your controller initialization, you just need:

(function init() {
    $scope.archivelist = archiveService.nextPage();
})();

However, as mentioned, it might be better to have an initial value like nextPage(1) and then specify the desired page to be sent to the factory method for proper handling.

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

Is there a way to automatically scroll the parent page's top when the user navigates within an iframe?

We are encountering an issue with the loading of the iFrame. When the iFrame loads on the client's page, we notice that the page location jumps around and, in most cases, the page focus is lower down the page. This requires users to scroll up to view ...

Ensure that the modal remains open in the event of a triggered keydown action, preventing it from automatically closing

I am currently toggling the visibility of some modals by adjusting their CSS properties. I would like them to remain displayed until there is no user interaction for a period of 3 seconds. Is there a way to achieve this using JavaScript? Preferably with Vu ...

What is the process for duplicating a set of elements within an svg file and displaying the duplicate at a specific location?

SVG <svg width="200" height="200"> <g id="group"> <rect x="10" y="10" width="50" height="20" fill="teal"></rect> <circle cx=" ...

generate a customized synopsis for users without storing any data in the database

In order to provide a summary of the user's choices without saving them to the database, I want to display it in a modal that has already been created. Despite finding some sources online, none of them have worked for me so far. Below is my HTML: &l ...

Guide on how to pass the chosen dropdown value from a custom component back to the main component

I've developed a customized MUI select component in React and have integrated it multiple times within another component as shown: customDropdown.js import * as React from 'react'; import FormControl from '@mui/material/FormControl&ap ...

Error message: Error in jQuery: Object is required for Internet

I have a button that is designed to trigger the opening of a jQuery UI Dialog when clicked. Strangely, it works perfectly in FF3, FF4, Chrome, and IE8 with ChromeFrame, but fails to function in regular IE8. The error message displayed simply states "Object ...

What is the process for updating the package-lock.json file in Laravel?

GateLab's security feature has identified some known vulnerabilities in the package-lock.json file that need to be updated. The message states: Known security vulnerabilities detected Dependency object-path Version < 0.11.5 Upgrade to ~> 0.11. ...

"Encountering a problem with jQuery AJAX - receiving an error message despite the status code being

Attempting to make a jQuery Ajax request using the following code: $.ajax({ url: '<MY_URL>', type: 'POST', contentType: 'application/json;charset=UTF-8', data: JSON.stringify(data), dataType: 'a ...

Convert the $rootScope object to a JSON string

In my web application, I am working on incorporating a basic bug-tracker feature. I ask the user to provide a written description of the issue, and then I aim to include a JSON version of $rootScope (values) that I will transmit using $http. Any suggesti ...

Converting CSV into an Array of Hash Tables

Currently, I am working on parsing a CSV file and creating an array of hashes. While I initially implemented this using my own code, I feel that it may not be the most efficient solution. My aim is to utilize the CSV-Parser library, but so far, I have only ...

Retrieving information from metaweather API and displaying it on an angularjs webpage

I am in the process of developing a basic weather application that can retrieve weather information for any city. The API I am using has two main stages: 1) Input the name of a city to get its "where on earth ID" (woeid). 2) Use the woeid to search for the ...

Send various pieces of information using Jquery/Ajax

I have encountered a challenge with my script - it currently only sends one value to the requested URL, but I now need it to handle two values. Unfortunately, I haven't been able to figure out how to do this. Each checkbox on the page is paired with ...

Viewing HTML web pages using Mozilla Firebox

Printing an HTML table with lots of content has been a challenge for me. Google Chrome didn't work, so I switched to Mozilla Firefox. However, now Firefox is breaking the page inside the table. My question is how can I trigger print preview in Firefox ...

Can anyone assist with troubleshooting the font size issue for a JavaScript tooltip on Joomla 1.5 with CK Forms?

My Joomla 1.5 site has CK Forms installed and is functioning properly, except for one issue: the tooltip on the captcha is not displaying correctly. It appears in a tiny 1px font size. Even though I have tried debugging using Firebug and confirmed that the ...

Automatically closing the AppDateTimePicker modal in Vuexy theme after selecting a date

I am currently developing a Vue.js application using the Vuexy theme. One issue I have encountered is with a datetimepicker within a modal. The problem arises when I try to select a date on the datetimepicker component - it closes the modal instead of stay ...

Strange behavior observed with Nuxt Js asyncData method returning values

Currently, I am engaged in a project using nuxt js/vue js. The project requires me to interact with multiple REST APIs. To accomplish this task, I am utilizing the asyncData() function provided by nuxt js to make the API calls within the page component. i ...

Turning JSON data into an array format, omitting the keys

Can someone help me with a query that will retrieve a specific column from the database and return it in this format: [ { "tenantName": "H&M" }, { "tenantName": "McDonalds" } ] I would like to transform ...

Tips for getting a sticky table header and including a limited number of columns, each with checkboxes or input fields

Encountering issues while trying to implement functionality with a jQuery library. One specific problem is the inability to interact with checkboxes on sticky columns, as well as difficulties clicking and typing in text fields. I am utilizing the jQuery S ...

Having trouble getting the onPress event to function properly on a custom button component in my React Native application

As a React Native beginner, I am currently working on a project where I am trying to create a custom button named "RoundedButton" using TouchableOpacity. However, when I attempt to trigger an event using onPress like , it does not seem to work for me. Here ...

The HTTP request is being executed twice for some reason unknown to me

import React, {useState, useEffect} from 'react' export function UseStateExample() { // This is a named export that must be used consistently with {} when importing/exporting. const [resourceType, setResourceType] = useState(null) useEffect ...