Issue with inheritance from Angular ModalCtrl to ServiceCtrl not functioning as expected

I've been working on linking models to services in order to update global models throughout my app, but it doesn't seem to be functioning as expected.

Recently, I delved into AngularJS and I suspect that I may have misunderstood my code. From what I grasp, a service should function as an instance, unlike a factory singleton. This setup should enable me to utilize a service to manage all $scoped models.

I'm attempting to connect my model like this:

model: {{ language.title }}

>>> ctrl1: $scope.language = langSrvic.store;

>>> srvic: langSrvic.store = myFactory;

>>> ctrl2: langSrvic.set('locale', 'fr');

>>> language instance store updated (should reflect change in controller 1 model)

Here is a working example of my code on jsFiddle

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

//Controller 1
app.controller('first', ['$scope', 'language', function($scope, language){
$scope.language = language.store;
    setTimeout(function(){
        console.log($scope.language.title); //My application
        console.log(language.store.title); //Something something french
    }, 1500);
}]);

//Language service
app.service('language', ['i18n', function(i18n){
return {
locale: 'en',
store: i18n['en'],
set: function(prop, val){
this[prop] = val;
this.store = i18n[this.locale];
}
}
}]);

//Factory - storing instead of an api temporarily
app.factory('i18n', [function(){
return {
en:{
title: 'My application'
},
fr:{
title: 'Something something french'
},
}
}]);

//Controller 2 - changing locale to fr which should update the instance store and so update the first scope
app.controller('second', ['$scope', 'language', function($scope, language){
    language.set('locale', 'fr');
    $scope.language = language.store;
}]);
<div ng-controller="first">
    {{ language.title }}
    <div ng-controller="second">
        {{ language.title }}
    </div>
</div>

Answer №1

You are making a reference to a different library object:

modify: function(key, value){
    this[key] = value;
    this.library = translations[this.language]; // This particular line updates the language library to a new object while Module A is still pointing at the old one
}

To see the resolution, check out the updated demo: http://jsfiddle.net/8b1apnfa/1/

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

Issue with function incorrectly computing values and returning NaN

My challenge is to develop a countdown timer, but it keeps returning NaN instead of counting down. I have multiple counters in place - one that counts down, another that counts up until the stop time specified by stoptime, and a third that kicks in after s ...

What would the equivalent Javascript implementation look like for this Python code that decodes a hex string and then encodes it to base64?

Currently, I am facing the challenge of transferring code from a Python script that decodes and encodes a string using a series of decode() and encode() functions. In Python, the code appears as follows: import codecs input = '3E061F00000E10FE' ...

An element generated through JavaScript fails to display on the webpage

As I navigate through the code with a foreach() loop, my goal is to generate a new div every time a firebase document containing the user's email is encountered. The script involves a blend of react js and javascript as I am still learning the ropes o ...

Error message indicating that the preflight request failed access control check in Angular 5 with JWT OAuth integration

After spending hours reading through several posts, I have yet to find a solution to a very common problem. It seems that in order for my JavaScript code to access the resource, the server must include the Access-Control-Allow-Origin header in the response ...

Unexpected server failure due to a new error occurring in the asynchronous authentication login function

This problem is really frustrating... I'm having trouble with a throw exception that causes my express server to crash in my async login function. The issue here is that the error isn't caught by the try/catch block. Even though the user data is ...

Are there any similar events to OnRouteChange in Angular?

I'm looking to execute a function every time a route changes in Angular. Does Angular have an event similar to OnRouteChange for this purpose? ...

Display a clean and simple toastr notification

Is there a way to specifically clear or hide just one toastr message when multiple messages are displayed, without clearing all of them at once? I've attempted the code below, but it didn't work for me. toastr.clear([toast]); For more informati ...

How to properly format credit card input using JavaScript or jQuery

I need to implement a feature where users input their credit card information, and once they complete the form, I want to display the credit card number in this format: xxxxxxxxxxxx1111 or xxxx-xxxx-xxxx-1111, without altering the actual input value. Is ...

designing the structure of directories and routes for express and angular applications

I'm new to using express and angular. After browsing through some answers in the forum, I stumbled upon the express angular seed project. My main question involves the directory structure and routing used in this seed project. In the angular seed ...

Having trouble with logging in/out, registration, and my submitPost function has suddenly ceased to work

Grunt is not showing any errors and when using the debugger "Error: [$injector:unpr] Unknown provider: AuthProvider <- Auth <- user <- NavCtrl also "Error: [$injector:unpr] Unknown provider: AuthProvider <- Auth <- user You can find the ...

Ways to quickly terminate a pipeline in a JavaScript transformation

Issue: I am facing a challenge with handling large files (>10GB). At times, I need to process the entire file while other times I only need to sample a few lines. The processing mechanism involves a pipeline: pipeline( inStream, ...

Displaying angularJS ui-grid columns in a lazy manner

Is there a way to efficiently load columns as needed? I have a large dataset with 5k columns and 100k rows. My framework is angularjs 1.5.7 along with angular-ui-grid ^3.x. The grid performs well with 100k rows and 100 columns, but when trying to load ove ...

The angular controller function is failing to set $scope.value

I've been facing an issue with setting an Angular variable value in a controller function that is created by a directive. For some reason, it doesn't seem to work when I try to assign the value within the controller function, even though it displ ...

Updating views with AJAX after database updates without the use of jQuery via PHP

Learning MVC and Ajax has been quite an adventure for me. I decided to build a site using PHP and MySQL, where I successfully implemented a new controller method to handle ajax requests. With the help of Ajax HTTPRequest, I am now able to update my databas ...

I am seeking assistance with my code. It is passing most of the test cases, but is failing only two without any error messages. What could

I recently started teaching myself programming, so please excuse me if my question seems a bit basic. One of the challenges on CodeCamp requires defining a function that takes an array with 2 values as input and returns the Least Common Multiple (LCM) of ...

how to transfer data from backend servlet to frontend javascript

Hey, I'm still learning about servlets so please excuse any confusion in my message! So basically, I'm trying to figure out how to pass a value from a servlet to JavaScript or even retrieve values from a servlet method within JavaScript. But I&ap ...

Having trouble accessing portlet resource URL from JavaScript in Liferay 6.2

I have been working with Liferay Portal 6.2 CE GA3 and I am facing an issue where I need to execute a custom portlet resource method from another portlet's JSP file. Below is the code snippet I am currently using. <a href ="#" onclick="myfunctio ...

Displaying two different dates in AngularJS without any repetition of the similar elements

How can I elegantly display a date range that includes two dates, without repeating information if it's the same for both dates? My idea is something like this: Tue, 05 May 2015 19:31-20:31 GMT Mon, 04 19:31 - Tue, 05 20:31 May 2015 It's accept ...

An issue has been identified with the functionality of an Ajax request within a partial view that is loaded through another Ajax request specifically in

Here is the current scenario within my ASP.NET MVC application: The parent page consists of 3 tabs, and the following javascript code has been implemented to handle the click events for each tab: Each function triggers a controller action (specified in t ...

Button with a Jquery icon design

Hello, I am currently working on implementing an icon button that can collapse and expand text. Although I have successfully implemented the logic for collapsing/expanding, I am facing difficulties in creating the actual icon button. The theme I am require ...