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 initiate an onload event from a script embedded within a jquery plugin?

Currently, I am in the process of developing a jQuery plugin. One issue that I have encountered involves a script tag being dynamically added for LivePerson.com. The script is supposed to trigger an onLoad function specified in the configuration. However, ...

Strategies for sending checkbox data to MySQL via AJAX and jQuery

Looking for assistance on passing values of multiple checkboxes to MySQL using arrays with AJAX (jQuery). I've written two separate code snippets, is there someone who can help me merge them? $(document).ready(function(){ var selected = []; $(&apo ...

Why do style assignments lose their motion when executed right after being made?

If you take a look at this specific fiddle in Webkit, you will see exactly what I am referring to. Is there a way to define the style of an element when it is first specified, and then its final state? I would like to be able to fully define a single-ste ...

Creating a precise regular expression for route length in Express JS

Currently, I am facing an issue while setting a route in my application. I want the URL parameter to be exactly 2 characters long, but unfortunately, the following code snippet is not producing the desired result: app.all('/:lng{2}?',function (r ...

Tips for implementing orderBy and filter in ng-repeat when working with an object instead of an array

I am facing a data structure that looks like this: $scope.people = { "ID123": { name_de: "Andre", name_en: "Anrew", age: 30, description: "He is the father of xyz and . . .", . . . ...

Refresh Angular component upon navigation

I have set up routes for my module: const routes: Routes = [ { path: ":level1/:level2/:level3", component: CategoriesComponent }, { path: ":level1/:level2", component: CategoriesComponent}, { path: ":level1", component: ...

Exploring the synergies between Angular Dragula and utilizing the $index property

Currently, I have implemented an ng-repeat of rows that can be rearranged using Angular Dragula. Despite successful drag-and-drop functionality, the $index in ng-repeat remains constant for each item even after reordering. The screenshot below depicts the ...

Authentication using tokens - JSON Web Tokens

While working with jsonwebtoken in Node, we generate a unique token for each user and return it to them. But when the user sends this token in the authentication header (Authentication: <token>), how does jwt differentiate between tokens from diffe ...

How to customize the arrow color of an expanded parent ExpansionPanel in material-ui

Currently facing a challenge in customizing material-ui themes to achieve the desired functionality. The goal is to have the expansion panels display a different arrow color when expanded for improved visibility. However, this customization should be appl ...

Move a <div> using a handle (without using JQuery)

I devised a plan to create a moveable div with a handle and came up with this code snippet: var mydragg = function() { return { move: function(divid, xpos, ypos) { divid.style.left = xpos + 'px'; divid.style.top = ypos + &apo ...

Tips for showcasing an image prior to uploading within a personalized design input file

I am facing an issue with displaying multiple images inside custom style input file labels before uploading them to the database. Currently, the script I am using only displays one image at a time and in random positions. My goal is to have each image ap ...

Tips for ensuring an animation is triggered only after Angular has fully initialized

Within this demonstration, the use of the dashOffset property initiates the animation for the dash-offset. For instance, upon entering a new percentage in the input field, the animation is activated. The code responsible for updating the dashOffset state ...

Finding the index and value of a specific HTML element with jQuery click event

I'm currently working on creating an Ajax function to delete items from a list using Jquery ajax. Here is the HTML structure: <ul> <li><a class="del"><span style="display:none;">1</span></a></li> <li& ...

The issue of the callback not being triggered by the sinon.js fakeServer when making a $.ajax call was encountered

I am currently working on a jasmine specification that involves testing a jQuery plugin I created: describe "plugins", -> beforeEach -> @server = sinon.fakeServer.create() afterEach -> @server.restore() describe "reviewStatu ...

The ReactJS redirect URL is constantly changing, yet the component fails to load

I recently started using reactjs and I encountered an issue with routing from an external js file. Here is the code in my navigation file, top-header.js import React from 'react'; import {BrowserRouter as Router, Link} from 'react-router-do ...

update and rejuvenate session information using Node.js and express-session

Currently, I am working with Node.js in conjunction with express-session. Within my codebase, there is session data containing user information. req.session.user Upon updating the user's information, I update the session with the new data and then r ...

Exploring the Depths of React by Cycling Through Arrays in Tabular Format

One issue I'm facing is that I have an array named paymentMethods which I'd like to iterate through in tabs. However, I seem to be struggling with the iteration part. To take a closer look at my code, please visit my codesandbox HERE <div& ...

Issues with the functionality of jQuery append and AngularJS ng-if not functioning

In my application using checkboxes, I control the visibility of charts with the ng-if directive and implement drag-and-drop functionality with angular-Dragula. The use of ng-if is essential for me as it allows me to manipulate visible div IDs and organize ...

The leave animation for Angular's ngAnimate and ng-view feature appears to be malfunctioning

angular version: 1.6.1 I am attempting to create a fade in/out effect for my ng-view element, however, I am encountering an issue where only the enter animation is functioning properly. This is the relevant HTML code: <main class="main" ng-view>&l ...

Encountering 404 Error in Production with NextJS Dynamic Routes

I'm currently working on a next.js project that includes a dynamic routes page. Rather than fetching projects, I simply import data from a local JSON file. While this setup works well during development, I encounter a 404 error for non-existent pages ...