creating a distinct angular service for every controller

Lately, I've been utilizing Angular services to store my commonly used codes that are required across different parts of my project. However, I have encountered an issue where variables in the service are shared between controllers. This means that if one controller modifies a variable, it impacts other controllers as well.

This behavior is not what I desire! I am looking for a solution similar to services but with an isolated environment for each individual controller. Is there any way to achieve this?

UPDATE:

app.service("myService",function(){
   this.variable = 1;
});

app.controller("loginCtrl",function($scope,myService){
    console.log(myService.variable); //outputs 1
    myService.variable++;
});

app.controller("signupCtrl",function($scope,myService){
    console.log(myService.variable); //outputs 2
});

I require each controller to use its own instance of myService (isolated from others).

Answer №1

AngularJS handles all services as singletons, allowing them to be shared and affected by multiple controllers. However, you can create a new instance of an injected service to ensure isolated scope, as long as you avoid injecting shared services into the new instance.

HTML:

<div ng-app="app">
    <div ng-controller="loginCtrl">
    </div>
    <div ng-controller="signupCtrl">
    </div>
</div>

JS:

var app = angular.module('app', []);

app.controller("loginCtrl", ['$scope', 'sharedService', function($scope, sharedService){
    var myService = sharedService.getInstance();
    console.log(myService.variable); //outputs 1
    myService.variable++;
}]);

app.controller("signupCtrl", ['$scope', 'sharedService', function($scope, sharedService){
    var myService = sharedService.getInstance();
    console.log(myService.variable); //outputs 1
}]);

app.factory('sharedService', [function () {
    return {
        getInstance: function () {
            return new instance();
        }
    }

    function instance () {
        this.variable = 1;
    }
}]);

Fiddle

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 is the best way to link an image in a React Component NPM module?

I have developed a date picker component in React and I'm currently working on uploading it to NPM. The component utilizes an external SVG file, but I am encountering issues with referencing that SVG file properly. Here's the structure of my fil ...

axios.get consistently delivers a Promise of type <Pending>

I have been searching for a solution to my issue, but so far none of the suggestions have worked for me. Below is the code that I am struggling with: const Element = () => { async function getEndData() { const data = (await getEnd()) ...

What is the reason why Prettier does not automatically format code in Visual Studio Code?

After installing and enabling ESLint and Prettier in my Nuxt application, I made the switch to Visual Studio Code. However, when I open a .vue file and use CMD+ Shift + P to select Format Document, my file remains unformatted. I even have the Prettier ex ...

Using AngularJS to Filter Array Elements

Here is a sample of the JSON data I am working with: products: [{ id: "1", model: "123", price: "123", spec: "213", image: "", brand: "213", category: "1", sub_category: "1", color: "1", size: "1", order: "1", ...

Using NodeJS and Express: redirection fails to load the specified endpoint

My current project involves a simple e-commerce web application running on localhost built with nodejs and express. Admins are required to register in order to gain access to functionalities such as adding, editing, and removing products from the product l ...

Incorporate unique color variables from the tailwind.config.js file

I am working on a project using nextjs and typescript, with tailwind for styling. In my tailwind.config.js file, I have defined some colors and a keyframe object. My issue is how to access these colors to use as background values in the keyframe. Here is ...

Guide on developing a personalized validation system with Vuetify regulations for verifying the presence of an item

I'm currently working on my first CRUD web app using Vue 2 + Vuetify, but I've hit a roadblock while trying to add validation to a form. Specifically, I need to ensure that no item with the same title already exists in the database. You can view ...

Issue: AngularJS not refreshing view after receiving server response

Currently, as I work on developing a mobile application, I've come across an issue related to relaying messages in the view after executing an ajax call and receiving data from the server. My goal is to display these messages to users only after they ...

Using a loop to iterate through a multidimensional array in Node.js or JavaScript, creating additional data and adding new key-value pairs

Here is an array of objects showcasing different intents and results : var finalresult = [{ "Date": "Wed Jan 15 2020 00:00:00 GMT+0530 (India Standard Time)", "data": [{ "intent": "delivery", "result": [{ "h ...

Warning: The use of jQuery load to trigger a Synchronous XMLHttpRequest on the main thread is now considered deprecated

$('#in-view-contents').load("/browse/".concat(selectedId), function(responseData){ var contentsLabelEl = document.getElementById("refined-contents-container"); contentsLabelEl.style.display = "block"; var arrayOfReloadScripts = ["/js/ ...

Creating dynamic backend routes in NextJS is a great way to add flexibility to

Is there a way for me to implement dynamic backend routes? I am working on an image hosting platform where users should be able to save their images on the server under unique domains like http://localhost/<random_id>. An example link would look so ...

Tips for utilizing global constants within the AngularJS constant

Exploring the implementation of Global constants within app configuration settings. In Constant.js var ApplicationConstants = { baseURL: "http://localhost:4200", } In appConfiguration.js (function () { 'use strict'; myModule.constan ...

Display an array containing date objects in a dropdown menu for users to select from

I am working with an API call that returns an array of objects. Each object in the array contains a date or timestamp in ISO format. Right after my render() method, I have the following code snippet: const pickerItems = this.props.currentData.trips.map(t ...

Find out if OpenAI's chat completion feature will trigger a function call or generate a message

In my NestJS application, I have integrated a chat feature that utilizes the openai createChatCompletion API to produce responses based on user input and send them back to the client in real-time. Now, with the introduction of function calls in the openai ...

Incapable of retrieving data from MongoDB due to a failure in fetching results using streams in Highland.js

I have recently started working with streams and I am experimenting with fetching data from my collection using reactive-superglue/highland.js (https://github.com/santillaner/reactive-superglue). var sg = require("reactive-superglue") var query = sg.mong ...

Encountering a no-loops/no-loops eslint error in node.js code while attempting to utilize the for and for-of loops

While working on my nodejs application, I have encountered an issue with es-lint giving linting errors for using 'for' and 'for-of' loops. The error message states error loops are not allowed no-loops/no-loops. Below is the snippet of c ...

The system is unable to interpret the symbol property 'Symbol(Symbol.iterator)' because it is not defined

I have created a custom .any() method for Array objects to loop through an array and check if any item passes a specified function: Array.prototype.any = (comparator) => { for(let item of this){ if(comparator(item)){ return true ...

The onClick function is failing to work properly, and I need to pass the value of 'cid' based on the result of the button

Is it possible to pass the 'courseid' to local storage when a button is clicked? I am having trouble with onclick not working. How can I retrieve the relevant 'courseid' in the onclick function based on the button clicked? handleClick ...

Navigate down to the bottom of the element located on the webpage

I'm trying to create a feature where clicking an anchor tag will smoothly scroll to a specific element on the page. Currently, I am using jquery scrollTo for this purpose. Here's the code snippet: $.scrollTo( this.hash, 1500, { easing:&apos ...

Error: Selenium-Javascript tests encountering an unexpected token issue

Having worked with Selenium using Java for a long time, I decided to switch gears and start writing Selenium scripts in JavaScript. I found a helpful guide to learn JavaScript with Selenium, which you can check out here. However, when I attempted to run n ...