Is it possible to load the factory in Angular JS just once?

I have set up a static json file to act as my server and fetch an array of orders from it. These orders are displayed in a table on my HTML page, with the ability to delete them individually. However, every time I refresh the HTML page, the full list is reloaded, including the orders that were deleted using the controller function.

Is there a way to load the data from the factory just once?

Below is the code snippet for my controller:

app.controller("MainPageCtrl", function($scope, getOrdersFactory)
{
    $scope.orders = [];
  
    // Fetching the data from the factory
    var dataPromise = getOrdersFactory.getDataFunc();
    dataPromise.then(function(data){
            $scope.orders = data.orders;
    });

    // Function to delete an order
    $scope.deleteOrder = function(order){
        // Find the index of the order
        var orderIndex = $scope.orders.indexOf(order);

        // Remove the order
        $scope.orders.splice(orderIndex, 1);
    };
});

Answer №1

By default, Angular services and factories are set up as singletons, meaning they are only loaded once. The issue you may be encountering is related to the controller being re-initialized whenever there is a route change. This results in the controller fetching the previous value from the factory.

To address this problem, consider implementing a setter function within your 'getOrdersFactory'.

If we assume that your 'getOrdersFactory' looks something like this:

app.factory('getOrdersFactory',function(){
 //code to read from file and set the content in orderDetails
 var orderDetails = contentsReadFromFile;  
 return{
  getDataFunc:function(){
   return orderDetails
  },
  setDataFunc:function(modifiedOrderDetails){
   orderDetails = modifiedOrderDetails;
   //code to update the content in the static file
  }
 }
}

The code responsible for reading from the static file will execute when you inject the factory for the first time. In your controller, make sure to set the order details using the delete function like so:

// Deletes an order.
$scope.deleteOrder = function(order){
// Find the index of the order.
var orderIndex = $scope.orders.indexOf(order);

// Delete the order.
$scope.orders.splice(orderIndex, 1);
getOrdersFactory.setDataFunc($scope.orders);
};

Answer №2

It seems like your data in $scope.orders is being lost. If this is the case, simply update

  dataPromise.then(function(data){
            $scope.orders = data.orders;
    });

to:

  dataPromise.then(function(data){
            $scope.orders = angular.copy(data.orders);
    });

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

Issue with Jquery's .html() function not functioning properly when trying to select HTML

I am currently working on a piece of code that looks like this: $price = $(element) > $('.main_paket_price').attr('name'); alert($price); Basically, I am trying to select an element inside element which has the class main_paket_pri ...

Collapsing tabs feature in Bootstrap 4

I am working on a project with Bootstrap 4 Tab. My goal is to initially hide all tab contents and then show them when the corresponding tab is clicked. I achieved this by removing the active class from the tab-pane div. However, I encountered an issue wher ...

Utilizing Express JS and Discord JS to assign roles

Hello there, I'm currently working on assigning a role to a user through a post request using the express framework. However, I'm facing some difficulties as I usually handle this process through the message function. Below is the code snippet: ...

Guidelines on resolving the issue of Unsupported platform for [email protected]: requested {"os":"darwin","arch":"any"} (existing: {"os":"win32","arch":"x64"})

Trying to install Parallelshell but encountering a persistent warning. I've checked the package file multiple times without finding a solution. Can someone assist me with this issue? ...

Is there a way to effortlessly launch a new window with just a single click?

I'm encountering an issue with a function that is supposed to open a new window when a button is clicked. Strangely, on the first click, nothing happens, but on the second click, the window finally opens. Here's my code: Script <script src ...

How can you simultaneously map data from two SQL tables in React?

In my script, I am retrieving data from a SQL table called device and displaying it in a table by mapping the content of device. My goal is to include a column that fetches information from another SQL table, group, but I am struggling to adjust the mappin ...

I am attempting to arrange variables based on the key of the json nested within another json

It's a bit challenging to condense my goal into one question, but I'll try my best to clarify. I currently have a JSON array that represents various HTML slider elements categorized within 3 control panes: Basic, Interface, and Advanced. Each pa ...

Is it compatible to use AngularJS with Visual Studio 2010?

I'm feeling uncertain about the performance of web applications using VS.Net 2010 and AngularJS due to the lack of posts or ideas from others. I would greatly appreciate it if someone could share their experiences. ...

Error Encountered: Duplicate Key Found in Repeater while using an Array called 'name'. The issue is resolved when using a different name

Here's the issue: when the variable is named 'name', the error 'dupes Duplicate Key in Repeater' appears! But why does this happen? Here's the code snippet: app.js var galleryModule = angular.module ("gallery",[]); var name ...

Combining vueJS and webpack to bring in fonts, CSS styles, and node_modules into your project

I've recently started working with Vue.js and Webpack, and I'm facing some challenges regarding the correct way to import and reference fonts, CSS, and node_modules in my project. My project structure looks like this, as set up by vue-cli: buil ...

What are the best methods for adjusting the size of a game's

I create games using HTML5/CSS/JS, but I am struggling to figure out how to make them scale to different screen resolutions. It seems like a simple task, but I can't seem to grasp it. SOLVED var RATIO = 480 / 800; // Initial ratio. function resize() ...

Selecting a value will cause other blocks to vanish

How do I hide other filter buttons when I select a value? Check out my code snippet below: const FilterBlock = props => { const { filterApi, filterState, filterFrontendInput, group, items, name, ...

Loading React.js components before data fetch is complete

My app is encountering an issue where it renders before the fetch operation is completed, resulting in incorrect rendering. Below is the code snippet: componentWillMount() { fetch('http://localhost:8081/milltime/login?users='+this.state.e ...

Evaluating the criteria and presenting two distinct notifications with setCustomValidity

When validating text fields in an HTML form, I am looking to check two conditions. Currently, the code below checks if the phone number entered is in the correct format and displays a message 'Enter a valid mobile number' if it is incorrect using ...

What steps can I take to replicate a 'heap limit Allocation failed' error?

Context I encountered a challenging issue where my program displayed a FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory This occurred when the memory usage reached around 512 mb Scavenge (reduce) 507.8 (518.9) -> 507.2 ...

Ways to utilize the Math.max and Math.min functions within an Array

Attempting to use this approach on an array to retrieve both the minimum and maximum values proved unsuccessful. var array = [3, 6, 1, 5, 0, -2, 3]; var min = Math.min( array ); var max = Math.max( array ); document.write(max); ...

How can you provide arguments to a mock function?

While using jest for unit testing, I am encountering the following line of code: jest.mock('../../requestBuilder'); In my project folder, there is a __mocks__ subfolder where I have stored my mock requestBuilder.js file. The jest unit test i ...

Using AngularJS, the functionality to choose options via ng-click is malfunctioning in the Chrome browser ecosystem

To achieve my goal, I need to incorporate ng-click in order to pass three parameters and then set them in my local json data based on the user's selection. <select> <option id="" value="">--Select--</option> <option ng-repeat="co ...

Picking an art exhibit to visit

Can you provide recommendations for a gallery suitable for my web project? The project utilizes: jQuery Bootstrap An ideal gallery would be based on jQuery. Here are the requirements and preferences: Compact CSS and JavaScript files. Utilization of the ...

Creating visual representations of class, organization, flow, or state diagrams using Vega or Vega-lite

I'm struggling to find an example of a state, class, flow chart, or org chart diagram created with Vega. Are there any available online? Vega seems like the perfect tool for this type of visualization, although it may be a bit complex. Without a star ...