Refreshing Angular Services: A Guide to Resetting Factories

My angular factory is quite intricate and structured like this:

app.factory("mainFcty", function(){
    return {
        a:"",
        b:"",
        c:""
    }
});

When users progress through the app and complete actions such as booking a service, they fill out the above form. However, when they add the data to a shopping cart and start over with mainFcty, old bindings seem to reappear and overwrite new data collected.

I need a solution to reset all previous bindings of mainFcty before continuing the process. Any suggestions on how to completely remove traces of the old data?

Your help is highly valued!

Answer №1

Start by setting up a values object and then transfer these values to the factory object that can be returned. Implement a method that allows for updating current values with default ones.

To see an example, check out: https://jsfiddle.net/xmtkg5tz/1/

var app = angular.module('myApp',[])
.factory("mainFcty", [function() { 
    var current_data = {}; 
    var default_values = { 
        a:"", 
        b:"I am a default that is not-empty", 
        c:"",
        resetData: function() { 
            console.log( 'Resetting')
            return current_data = angular.extend( current_data, default_values ); 
       } 
    }; 
    default_values.resetData();
    return current_data;
}])
.controller('exampleCtrl',['$scope', 'mainFcty', function($scope,mainFcty) {
    $scope.fcty = mainFcty;
    $scope.submit = function() { 
        console.log( 'reset?', $scope.fcty.a, $scope.fcty.b, $scope.fcty.c ); 
        console.log( 'Before:', mainFcty );
        mainFcty.resetData(); 
        console.log( 'After:', mainFcty ); 
    };
}]);

Answer №2

One technique that has worked well for me is to declare the variable at the beginning of the factory, then call reset, and whenever necessary, use reset to reset the variable.


.factory('sharedDataUserFlowService', function () {
        var serviceVariables;
        resetData();
        return {
            resetData: resetData,
            triggerFormCheck: triggerFormCheck
        };

        function resetData() {
             serviceVariables = {
                 triggerFormValidateCheck: false,
                 triggerBlockStageVariable: null,
                 isFormValid: false,
                 blockedStage: null,
                 isProcessEnd: false
             }
        }

        function triggerFormCheck() {
            serviceVariables.triggerFormValidateCheck = !serviceVariables.triggerFormValidateCheck;
        }

This can be called from anywhere it is injected using

sharedDataUserFlowService.resetData();

Best of luck!

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 encountered: `unexpected token within ES6 map() function`

Do you see any issues with this code snippet? render(){ return ( var users= this.state.users.map(user => <li key={user.id}>{user.name}</li> ) <ul>{users}</ul> ) } I am receiving an error mes ...

What is the reason for and <br> not functioning in a string?

I am encountering an issue when attempting to print the content of an object. Some of the properties within the object contain tags, making it challenging to create new elements in JavaScript without knowing which properties will include these tags. How ...

Attempting to implement usedispatch hook in combination with userefs, however, encountering issues with functionality

I've been exploring the Redux useDispatch hook lately. I created a simple app for taking notes in a todo list format. However, I am facing an issue with useDispatch as it's not working for me and I keep encountering this error: Module build faile ...

Is it necessary to dispose of node.js domains? When is the appropriate time to do so?

In my Express application, I utilize domains for each incoming request. To ensure that all subsequent middlewares are executed within a domain, I've implemented a middleware. app.use(function(req, res, next) { var d = domain.create(); d.req ...

How to prevent v-menu from overlapping a navbar in Vue.js

Exploring the examples on the main page of Vuetify, we come across the v-menu component showcased in detail. Check it out here: https://vuetifyjs.com/en/components/menus/#accessibility If you activate any of the buttons to open the v-menu and then scroll ...

Error encountered: The function 'showErrorMessage' is not exported from the file '../helpers/alerts'

Within the directory ../helpers/alerts, there is a file called alerts.js const displaySuccessMessage = (success) => { <div className="alert alert-success">{success}</div> } const displayErrorMessage = (error) => { <di ...

UI thread was blocked due to withProgress being invoked from an external library function

Currently enhancing an extension that is almost finished, but facing a challenge in adding visual cues for lengthy operations. Initially suspected a missing async/await in the code, but struggling to identify the cause. The progress indicator isn't di ...

Node.js user update complete

I am currently working on enabling users to edit their profiles. However, the code I have set up does not seem to be functioning as expected. The form I am using looks like this: <form action="/dashboard/users/edit/:id" method="put"> And my route ...

The Hidden Div containing NicEdit is now shrunk down to a smaller size

Attempting to integrate the NicEdit editor for a hidden textarea stored within a div has presented some challenges. The goal is for the targeted textarea's parent div to be revealed upon the user clicking a button, with the textarea's width set t ...

Error code 403 has been reported by Stripe's payment_init.php as a forbidden request

Having some trouble incorporating a Stripe payment method into my web application. I've hit a roadblock: payment_init.php isn't loading when I'm redirected to the page. Instead, I'm greeted with a 403 Forbidden error code ("Forbidden. Y ...

Simplifying complex JSON structures by un-nesting arrays

Within my Formik form, I have 3 fields: MemberMemberID, EventEventID, and event_date. This form represents an event (such as a Tuesday club) taking place on a specific date and attended by various members. Formik stores the data in key-value pairs within ...

What is the process for showcasing a local notification within my application?

Here is the code snippet I am working with: import { LocalNotifications } from '@ionic-native/local-notifications'; @Component({ selector: 'app-home', templateUrl: 'home.page.html', styleUrls: ['home.page.scs ...

I have a vision of creating a unique Countdown Stopwatch that meets all my

I'm looking to create a custom countdown stopwatch where I can set the time and watch it count down to 0:00. The stopwatch should have three buttons: Start, Stop, and Reset. I've searched multiple websites for what I need but haven't found ...

Tips for eliminating the domain name from the src URL attribute using Jquery

Is there a way to extract the img src attribute and retrieve only the image path without the domain name included? var imgurl = "http://nitseditor.dev/img/home/bg.jpg"; For instance, I would like to display img/home/bg.jpg instead of the full URL. Any id ...

Exploring the combination of Babel and Next.js: Integrating custom scripts into a project

Hello, I am currently learning next.js and facing a common issue that I need help with. I have created my own ES6 JavaScript library and now I want to convert it to babel so I can use it in my next.js application. Is there a way to configure babel for sp ...

Customizing Django forms.Textarea in template or declaring in models is essential for creating a unique

Within my models, I have a forms.Form that includes a textarea field: answer1 = forms.CharField(label='Answer 1', widget=forms.Textarea(attrs={"placeholder":"Type your answer...", "rows":6, "cols":45}), max_length=150) When it comes to views: ...

I am unsure about the installation process of AngularJS in my application and I need to update it

I am currently working on an application that utilizes AngularJS v1.2.12, however, we did not create it ourselves. I have been trying to figure out how to upgrade from v1.2.12 to v1.7.0, but it appears that it was installed in a different way. All the sug ...

What is the best way to add methods to underscore without making them available globally?

Have you added multiple methods to underscore within your package? _.mixin({ foo: function() {}, bar: function() {} //etc }); If you're concerned about potential conflicts with the main application or other packages, what's the best way ...

What sets Protractor apart from Grunt?

According to the Protractor website (http://www.protractortest.org/#/infrastructure), Protractor utilizes Selenium for browser automation. However, when browsing through the Grunt website (http://gruntjs.com/), it's mentioned that Grunt is also used f ...

Is there a way to change the text (price) when I select an option?

<div class="single-pro-details"> <!--Customize in the CSS--> <h6>Home / Beats</h6> <h4>Unique Lil Tecca Type Beat - New Love</h4> <h2 id="price">$ ...