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

Error alert: The function is declared but appears as undefined

Below is the javascript function I created: <script type="text/javascript"> function rate_prof(opcode, prof_id) { $.ajax({ alert('Got an error dude'); type: "POST", url: "/caller/", data: { ...

The ng-model in Angular is unable to capture the initial input value on load

I am currently using a window onload script to obtain longitude and latitude data and pass them to hidden input values. $(function() { window.onload = getLocation; var geo = navigator.geolocation; function getLocation() { if (geo) { geo ...

Exploring JSON data with multiple nested layers of iteration

I'm currently working on a project that involves parsing through a JSON file with a complex structure. I've been attempting to extract a link to an image within the JSON data, but my current approach is resulting in an error. Below you'll fi ...

The res.download() function in Express is failing to deliver the accurate URL to the client

When trying to utilize the res.download() method for downloading specific files from a server, there is an issue where triggering the res.download does not redirect the client to the correct URL. The files intended for download are located in a directory s ...

No output is displayed in the absence of errors. The program is functioning correctly

app.js angular.module('app', ['ionic', 'ui.router']) .config(('$urlRouterProvider', '$stateProvider', function($urlRouterProvider,$stateProvider){ $urlRouterProvider.otherwise('/'); $sta ...

A <div> with relative positioning is inhibiting the visibility of absolutely positioned elements without any visible overlap

Recently, I encountered a strange issue on my webpage: Image of page The lines on the left side are supposed to be displayed behind or on top of the text box. However, when I increase their z-index, the lines extend all the way to the top of the page and g ...

I am experiencing an issue where my JavaScript code does not redirect users to the next page even

I'm experiencing an issue with this code where it opens another webpage while leaving the login screen active. I've tried multiple ways to redirect it, such as window.location.href and window.location.replace, but nothing seems to be working. Ide ...

Trouble with fetching data for Line Chart via jQuery AJAX and ASP.NET MVC

I am working on incorporating a simple line chart from Google Charts into my project, but I am facing an issue with the data not loading correctly. I only require two values to be displayed: the hours worked and the days of the particular month. While I ca ...

Display the item for which the date is more recent than today's date

Is there a way to display only upcoming 'events' on my page based on their event_date? <% for (let event of events){%> <div class="card mb-3"> <div class="row"> <div class="col ...

Personalize the marker design within the Wikitude SDK using JavaScript

Currently, I am developing an augmented reality view in Android using the wikitude-sdk. As part of the project, I am displaying markers on the screen and now I am looking to customize the marker view using the AR.HtmlDrawable method offered by the ...

Dynamically insert <td> elements into <tr> element using both jQuery and JavaScript

I am facing an issue with adding a new table data (td) element dynamically to the first table row (tr) in my JavaScript code. Here is the original table before adding the new td element: <table> <tbody> <tr> <t ...

I am trying to access a value saved in a service in Angular 8 component and use it in other services. Can anyone help

Setting a value through a component export class UniqueComponent { constructor(service:UniqueService){ } count =0 ; onRefresh(){ this.service.count = 1; } } Using the value in the service UniqueService{ count:any; doSomething(){ //using count ...

Trouble handling Ajax response

I have two JSP files described below. The parent JSP page contains a Select dropdown box with two options. Another JSP file, dispTable.jsp, displays select boxes inside a table. If the user selects "one" from the dropdown in the parent.jsp page, I want ...

Drop-down options disappear upon refreshing the page

Code snippet for sending value to server using AJAX in JavaScript In my script, the status value may vary for each vulnerable name. When selecting a status option and storing it in the database through AJAX, the selected value is lost after refreshing th ...

Keep elements in position when their bottom edge becomes visible while scrolling

This task may appear intricate, but I will do my best to explain it! I want to create a continuous scrolling article display similar to Bloomberg Politics (), but with a slight twist. My idea is to have the current article's bottom edge stick to the ...

What is the best way to dismiss the ant-design-vue select option when the mouse moves away?

<a-select showSearch placeholder="Select a person" optionFilterProp="children" style="width: 200px" :open="isOpen" @mouseenter="handleOpenSelect" @mouseleave="handleCloseSelect" > <a-select-option value="jack"> ...

What is the duration that browsers retain downloaded assets during a single session?

Is it necessary to preload data from the server in order to have immediate access when needed? The data is stored in a file named "data.json". Initially, I considered storing data.json in an object and referencing it whenever required. However, given tha ...

Creating an interactive map on an image using HTML and drawing circles

I've been experimenting with drawing circles on images using the map property in HTML. I have an image set up, and when clicking on the image in JavaScript, I'm adding the area coordinates for the map property. However, I keep encountering a null ...

Vue - Passing a parent's ref to a child component as a prop

Is there a way to pass the current component's reference to a child component in Vue.js? <template> <div class="screen" ref="screen"> <child-component :screenRef="screenRef"> </child-component> </div ...

What is the best way to implement an AppBar that fades in and out when scrolling within a div?

I'm trying to implement a Scrollable AppBar that hides on scroll down and reappears when scrolling up. Check out this image for reference To achieve this functionality, I am following the guidelines provided by Material-UI documentation export defa ...