Troubleshooting: Why is $watch failing to track changes on factory variables in Angular

I have created a factory named SharedService as shown below:

  angular.module('Fms').factory('SharedService', function() 
  {
    var userdetails=false;
    return userdetails;
  })

Below controllers utilize this factory:

angular.module('Fms').controller('mainCtrl',['$scope','SharedService',function($scope,SharedService)
 {
    $scope.userdetails=SharedService;
    $scope.$watch(SharedService, function(newValue, oldValue, scope) 
    {
        console.log(SharedService)
        if (newValue && newValue !== oldValue) 
        {
            $scope.userdetails = SharedService;
        }
    });
 }]);


angular.module("Fms").controller('LoginCtrl',['$scope','$http','$location','SharedService',function($scope,$http,$location,SharedService)
{
$scope.results ="";
$scope.name ="";
$scope.pass ="";
$scope.errormessage="";
$scope.login=function()
{
    $http(
    {   
        method: 'get',
        url: '/login',
        params : {username:$scope.name,password:$scope.pass},
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    }).
    success(function(response) 
    {
        if(response=="success")
        {
            $scope.errormessage="";
            SharedService.userdetails=true;
            $location.path("/home")

        }
        else
        {
            $scope.errormessage="Enter valid Username & Password";
                SharedService.userdetails=false;


        }
    }).
    error(function(response) 
    {

    });
}
 }]);

The issue is that I need to update the `userdetails` variable in the SharedService factory from the LoginCtrl controller based on authentication response. Also, the `$scope.userdetails=SharedService;` in mainCtrl needs to be updated using $watch, but it's not working as expected.

Answer №1

If you're looking to optimize your factory, consider structuring it like this:

angular.module('Fms').factory('SharedService', function() {
    var _userdetails = false;

    return {
        changeUserDetails: function(details) { 
            _userdetails = details 
        },
        getUserDetails: function() { 
            return _userdetails 
        }    
    }
})

In your mainCtrl, make sure to access the user details by calling:

$scope.userdetails = SharedService.getUserDetails();
$scope.$watch(function(){ return SharedService.getUserDetails()}, function(newValue, oldValue) {
    if (newValue && newValue !== oldValue) {
        $scope.userdetails = SharedService.getUserDetails();
    }
});

Be sure to update the user details in your loginCtrl using:

SharedService.changeUserDetails(true);

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

Using Angular 2 routes to navigate to various applications

I'm currently developing multiple versions of my application in different languages. Utilizing AOT (ahead of time) compilations, the end result is static deployable sites organized in a structure like this: dist - index.html -- default entry file f ...

You can only set headers once during the initial request; any additional attempts to set headers will result in an

I encountered a specific issue with the error message "Can't set headers after they are sent". Here is the relevant code snippet: create: (request, response, next) -> socket = @app.socket # # This method will be used to call the right method ins ...

Using jQuery to select a specific checkbox from a group of checkboxes with identical IDs

There is an issue with multiple checkboxes having the same ID in an asp.net repeater control. Users can select either email or phone against each record in the repeater rows. In the example below, there are two rows. If you select the email icon in the fi ...

React - Defining a global variable within a React component

Can you explain the process to me? I am trying to set up a variable within a react component class so that I can utilize it in multiple sections of my application. Here is what I have attempted: class ColorPick extends React.Component { colorInput; ...

Utilizing an Angular foreach loop for restructuring JSON data

I currently have an ng-repeat function that outputs arrays of objects in the following format: [ {"day":"10","title":"day","summary":"summary","description":"ok","_id":"53f25185bffedb83d8348b22"}, {"day":"3","title":"day","summary":"summary","description" ...

Conceal the element if the offspring is devoid of content

I want to implement a feature where a div is hidden when its child element is empty. To achieve this, I aim to assign the class .no-content to the div if it contains no elements. Below is my existing code with spaces: <div class="ee-posts-list&quo ...

The 'load()' event method in jQuery does not function properly within the 'ready()' event method on mobile browsers

After testing on Firefox mobile and Chrome mobile browsers, I found that my code works perfectly on computer browsers. Below is the code I have inside the ready() and load() event methods: $(document).ready(function(){ $(window).on('load hashchan ...

The function maybeStripe.apply is not defined

Greetings, Encountering a Stripe error in Gatsby upon page load Error: Uncaught (in promise) TypeError: maybeStripe.apply is not a function import React, { useEffect, useState } from 'react'; import { loadStripe } from '@stripe/str ...

Can you please enlighten me on how to obtain the HTML for the selected area of the cursor in Tiptap?

I've successfully created a customized text editing tool using tiptap/react. My question is, how can I retrieve the html or json of a selected area when I highlight text with the cursor? For instance, if I have a custom tag 'say-as' within ...

Incorporate Push Notifications with AngularJS in Laravel 4

I am currently developing a straightforward application using Laravel 4 for the backend, Angular JS for the frontend, and MySql. At the moment, I am utilizing long polling to check for any updates in the database, which requires me to send an $http reques ...

Encountering CORS Error Despite Having CORS Enabled in Nest.js/Angular Application

Currently, I am in the process of developing a small calculator application as a means to gain expertise in Nest.js and Angular. In order to achieve this, I have established a server that hosts a basic web API equipped with several endpoints. One particula ...

A collection of radio button groupings organized using ng-repeat

I have a collection of objects containing nested arrays of objects. I need to organize these objects into groups based on the number of parent objects, each group needing radio buttons corresponding to the number of child objects. Here is an example of th ...

The functionality of clicking on a jQuery-generated element seems to be malfunctioning

When using Jquery, I am able to create an element and assign it the class .book: jQuery('<div/>', { name: "my name", class: 'book', text: 'Bookmark', }).appendTo('body'); I then wanted to add funct ...

An effective method for targeting a specific button within a CSS file

I have multiple button tags in my code, but I need to style a specific one using CSS. How can I target this particular button and apply styles only to it while leaving the others unchanged? Do I need to assign the button to a variable and reference that va ...

Troubleshooting issues with Vue CLI 4 and A-Frame: Finding solutions for

Recently, I've been working on creating a VR web app using Vue cli 4.2.3 and aframe.io. However, I encountered numerous error messages related to aframe's components. [Vue warn]: Unknown custom element: <a-scene> - did you register the com ...

Using Angular, we can assign an array iteration as the value for a dropdown option in

Following the controller logic: $scope.form_data = { day: 'Day' }; $scope.days = [ 'Day',1,2,3,4,5,6,7,8,9,10, 11,12,13,14,15,16,17,18,19,20, 21,22,23,24,25,26,27,28,29,30, 31 ]; In the html section: <select n ...

Is it possible to access the operating system's native emoji picker directly from a website?

While there are numerous javascript plugins and libraries available for allowing users to select emojis for text inputs, both Windows and Mac operating systems already have their own native emoji pickers accessible via ⊞ Win. or CTRL⌘Space. Is there a ...

Is there a way for multiple controllers to share a single template using controllerAs syntax?

Assume there are two controllers defined as follows: function MainController() { this.hello = function() { // does something } } function AnotherController() { this.hello = function() { // does something else } } The controllerAs for Mai ...

Calculate the number of elements shared between two arrays using JavaScript

I am working with two arrays of objects and I need to determine how many different types of cars we have. The first array contains the IDs of all the cars, while the second array contains information about the types of cars. Here is the data: var arr = ...

How can I turn off autocomplete in MUI textfields?

Currently, I am working with the latest version of mui. Within my user contact info form, there is a zip code field that I do not want to be auto completed if the value is null. However, despite my efforts, it continues to autocomplete with the email saved ...