AngularJS is failing to update the shared service model

Utilizing AngularJS, my application contains two controllers that share a common service. When triggering an event controlled by the portalController function (specifically the setLang() function), I notice that the model of the applicationController does not update.

This issue seems to be specific to Firefox and Chrome, as it works unexpectedly fine in IE8.

PortalController

(function () {
'use strict';

var controllers = angular.module('portal.controllers');

controllers.controller('portalController', function portalController($scope, UserService, NavigationService, $translate) {
    $scope.User = UserService.getUserinfo();

    $scope.setLang = function (langKey) {
        $translate.uses(langKey);
        UserService.setUserinfoLocale(langKey);
        UserService.getUserApplications(Constants.key_ESS);
        UserService.getUserApplications(Constants.key_MED);
        UserService.getUserApplications(Constants.key_SVF);
        $.removeCookie(Constants.cookie_locale);
        var domain = document.domain;
        if (domain.indexOf(Constants.context_acc) != -1 || domain.indexOf(Constants.context_prd) != -1 || domain.indexOf(Constants.context_tst) != -1) {
            domain = "." + domain;
            $.cookie(Constants.cookie_locale, langKey, {path:"/", domain:domain});
        } else {
            $.cookie(Constants.cookie_locale, langKey, {path:"/"});
        }
    };

    $scope.logout = function () {
        NavigationService.logout();
    };


    $translate.uses(UserService.getUserinfoLocale());


});
//mainController.$inject = ['$scope','UserInfo'];


}());

ApplicationController

(function () {
'use strict';

var controllers = angular.module('portal.controllers');

controllers.controller('applicationController', function ($scope, UserService) {
    $scope.ESS = UserService.getUserApplications(Constants.key_ESS);
    $scope.SVF = UserService.getUserApplications(Constants.key_SVF);
    $scope.MED = UserService.getUserApplications(Constants.key_MED);
});
}());

The shared UserService

UserService.prototype.getUserApplications = function(entity){
    var locale = this.getUserinfoLocale();
        return this.userApplications.query({locale: locale, entity: entity});
};

JSFiddle

http://jsfiddle.net/GFVYC/1/

Answer №1

The issue I encountered stemmed from my use of $scope instead of $rootScope. The data was being updated by the first controller in the service, but the second controller remained unaware of this change:

Snippet from the first controller signaling $rootScope of a change

$scope.setLang = function(locale){
        $rootScope.data = sharedService.getData(locale);
};

Snippet from the second controller listening for changes

$rootScope.$watch('data', function(newValue) {
        $scope.data = newValue;
    });

Below are links to two versions of the fiddle, one incorrect and the other correct, for those encountering a similar issue:

Incorrect: http://jsfiddle.net/GFVYC/1/
Correct: http://jsfiddle.net/GFVYC/4/

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

Why is my AngularJS controller receiving 'undefined' data from my service request?

Question: I am facing an issue where my service is successfully retrieving the necessary data, but my controller is not able to access it. What could be causing this problem? Service: Below is the code that my controller calls. // search.service.js (func ...

Utilize the push method to form a new array

var teamMembers = [ ['John D. Adams', '1959-1967', 'Ohio'], ['Dawson Mathis', '1971-1981', 'Georgia'], ]; To generate this dynamically, I am implementing the code below: var data = ne ...

utilizing vuex store within a JavaScript document

Currently, I'm encountering an issue while attempting to access my store from a helper function file: import store from '../store' let auth = store.getters.config.urls.auth An error is being logged: Uncaught TypeError: Cannot read prop ...

What is the process for displaying information from a database on a model popup box?

I am working on displaying books in the Index view that are retrieved from a database. Each book has a button underneath it. The goal is to have a modal box appear when these buttons are clicked, showing details of the corresponding book such as the book i ...

Organizing information in local storage using an array and converting it to a string

After storing user inputs (Worker's name, Car Vin, Start time and End time) in the local storage, you want to sort the employees' names in alphabetical order. The question is where should the code be placed and how should it be written? // Car C ...

Is there a convenient method to combine arrays of objects in JavaScript using ellipses or an equivalent approach?

let array = [ {id: 1, data: {foo: "bar 1"}}, {id: 2, data: {foo: "bar 2"}} ]; //If ID doesn't exist, add new element to the array array = [...array, {id: 3, data: {foo: "bar 3"}}] console.log(array); //If ID exists, replace data object with new ...

"Implementing ASP.NET MVC4 with Razor: Dynamically filtering a dropdown list based on the selected value from another dropdown

Currently, I am facing a challenge where I need to filter the options of a dropdown list based on the value selected from another dropdown. Within my database, there are tables containing all countries and all cities in the world, with a foreign key linkin ...

Issue with CORS when starting SAM local API

I have encountered a CORS issue while using AWS CDK (Typescript) and running SAM local start-api to launch an API connected to lambda resolvers. The problem arises when attempting to access the API from a web browser. Below is the code snippet causing the ...

What is the most effective method for incorporating keyframes using JavaScript in a dynamic way?

Is there a way to animate an HTML element by using a variable with keyframes, but without directly manipulating the DOM? Below is the HTML code: <div class="pawn" id="pawn1"></div> Here is the CSS keyframes code: @keyframe ...

React component allowing for the reuse of avatars

As a novice in React, I've encountered a challenge. My goal is to develop a simple reusable component using MUI. Specifically, I aim to create an avatar component that can be easily customized with different images when called upon. I want the flexibi ...

Resolved issue with sticky header movement after scrolling event

I've been working on a sticky header code, but I'm having trouble achieving a smooth scroll transition. The fixed header seems to jump after just one scroll. Here is the basic HTML structure: <div class="headerWrapper"> <div id="to ...

Automatically refreshing controller functionality in CodeIgniter

Greetings everyone, I'm looking for a way to automatically refresh a controller function every 5 seconds. Currently, I am using header('Refresh: 10.2'); within the controller function like this: public function delete() { heade ...

Are multiple .then(..) clauses in Javascript promises better than just using one .then(..) clause?

In this particular scenario, I have set up a basic 'toy' node.js server that responds with the following JSON object: { "message" : "hello there" } This response is triggered by making a GET request to "http://localhost:3060/" So, it's reall ...

The malfunctioning buttons are a result of embedding PHP code within a JavaScript if-query

I am experiencing an issue where my buttons are not functioning properly, preventing me from clicking on them. All variables have been correctly assigned values. Can someone assist me in resolving this? Thank you. ?> <script> ...

angularDynamicLocation does not contain the specified localeLocationPattern

I am using angular-translate to handle localization with angular dynamic localization. I have attempted the following code, but for some reason the localization is not changing. I suspect that the issue lies in angular not being able to locate localeLocati ...

Storing the API key returned by the Node.js store as a variable was

Just starting out with node and experimenting with A node.js library for the Pardot API I provide my userKey, email, and password to pardot, which returns an api_key. This is the code snippet I am using for authentication. Upon running my node server, I ...

Obtain the content of a clicked item on the following page using NextJs

I am currently working on a nextjs app that displays a list of 10 movies on the homepage, each with a Button / Link that leads to a specific page for that movie where all its content is shown. Initially, I tried adding the movie id to the Link like this: ...

What is the best way to implement a 5-second delay after the timer reaches 00:00?

I am in the process of creating a countdown timer for an application. Once the timer reaches 00:00, I would like to add a 5-second delay before it starts counting down again. How can I achieve this using setTimeout()? function initiateTimer(duration, di ...

Having trouble retrieving the $_SESSION variable accurately from AngularJS

I am working with angularjs and need to retrieve a php session variable. I have created a php file named session.php with the following content: $_SESSION['phone'] = '55551864'; return json_encode($_SESSION['phone']); In my ...

Update the ng-view within ng-view with new content

Greetings, I am currently in the process of developing a single page application using Angular. Below is an excerpt from my index.html file: <!DOCTYPE html> <html lang="en" ng-app="onlineApp"> <head> <meta charset="UTF-8"> ...