AngularJs monitoring changes in service

Why does changing the message in the service not affect the displayed message in 1, 2, 3 cases?

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

app.factory('Message', function() {
  return {message: "why is this message not changing"};
});

app.controller('Changer', function($scope, Message) {
  Message.message = "first" // (1)

  $scope.changeItems = function() {
    Message.message = "second" // (2)
  }
});

app.controller('Listener', function($scope, Message) {
  $scope.message = Message.message
  Message.message = "third" // (3)
});

This is how it appears in my view:

<div ng-controller="Listener">
  {{ message }}  
</div>

<div ng-controller="Changer">
  <button ng-click="changeItems()">change message</button>
</div>

I have also created an example on Plunker for reference http://plnkr.co/edit/BUPS6U0S7ktDEkH9dZTZ?p=preview

Answer №1

The main reason for this behavior is that the "Listener" controller is initialized first since it appears first in the View's HTML structure. If you change the order, you will notice the "First" message instead.

Additionally, it is essential to note that when you set a reference to a string and later modify the string, the reference is lost. This is why it is more effective to reference an object and then render the object's property in the following manner:

Controller:

$scope.Message = Message

View:

{{Message.message}}

By following this approach, you can ensure that the reference is maintained properly.

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

Customizing the main icon in the Windows 10 Action Center through a notification from Microsoft Edge

I am facing an issue with setting the top icon of a notification sent from a website in Microsoft Edge. Let's consider this code as an example: Notification.requestPermission(function (permission) { if (permission == "granted") { new ...

Exploring VueJs 3's Composition API with Jest: Testing the emission of input component events

I need help testing the event emitting functionality of a VueJs 3 input component. Below is my current code: TextInput <template> <input v-model="input" /> </template> <script> import { watch } from '@vue/composition-api&ap ...

Tips for integrating CSS keyframes in MUI v5 (using emotion)

Hey there! I'm currently working on adding some spinning text, similar to a carousel, using keyframes in my React app. The setup involves MUI v5 with @emotion. Basically, I want a "box" element to show different words every few seconds with a rotating ...

Utilizing jQuery for dynamic horizontal positioning of background images in CSS

Is there a way to set only the horizontal background property? I've tried using background-position-x and it works in Chrome, Safari, and IE, but not in Firefox or Opera. Additionally, I would like to dynamically set the left value of the position. ...

Determine if the input text field contains any text and store it in a variable using jQuery

I'm working on a form that includes radiobuttons and textfields. To keep track of the number of checked radiobuttons, I use this code: var $answeredRadiobuttons = $questions.find("input:radio:checked").length; But how do I store the number of textf ...

Troubleshooting issue with multer code failing to save files in designated directory within nodejs server when using reactjs frontend

I'm facing an issue while trying to upload a photo into my server folder. Even though the submission process adds the picture to my database, it does not display the image in my server folder. The frontend of my application is built using React JS, an ...

"Enhance User Experience with Material UI Autocomplete feature that allows for multiple

I am encountering an issue with a material ui auto component that I am currently working on. The component's code looks like this: <Autocomplete multiple options={props.cats} defaultValue={editRequest? ...

What could be causing the error to occur at the beginning of the application launch

I am currently using AngularJS version 1.6.4 for my project and encountering an error in the console debugger when the application starts: http://errors.angularjs.org/1.6.4/$injector/nomod?p0=reports Below is the code snippet of my main module: angular. ...

typescript unconventional syntax for object types

As I was going through the TypeScript handbook, I stumbled upon this example: interface Shape { color: string; } interface Square extends Shape { sideLength: number; } var square = <Square>{}; square.color = "blue"; square.sideLength = 10; ...

Dynamic Dropdown Menu in Zend Framework with Autofill Feature

I've been diligently working on a code to automatically populate dropdowns onchange, right after selecting the necessary values from an autocomplete search field. However, I am facing an issue where my autofill feature fails to work after making a sel ...

React-Native has reached the maximum update depth, please check the new state

When I try to add and change the number (setNum(number+1)), I encounter an error message stating: Maximum update depth exceeded. This issue may arise when a component repetitively calls setState inside componentWillUpdate or componentDidUpdate. React enfor ...

unable to press the electron button

I am currently working on a project that involves connecting PCs together for screencasting. While following an online coding tutorial, I encountered an issue with clicking the button to generate the ID code. Here is the code snippet from app.js: // Code ...

Step-by-step guide on displaying a tag image in HTML using html2canvas

html2canvas($('#header'), { allowTaint: true, onrendered: function (canvas) { var imgData = canvas.toDataURL("image/png"); console.log(imgData); } }); click here for an example ...

Exploring numerical elements in interactive content

Struggling with the Wikipedia API and encountering issues with the results that are returned. {"query":{ "pages":{ "48636":{ "pageid":48636, Concerned about how to access a specific ID (such as 48636) without knowing it in advance ...

Issue with v-model not connecting to app.js in Laravel and Vue.js framework

Snippet from app.js const app = new Vue({ el: '#app', router, data:{ banana:'' } }); Code found in master.blade.php <div class="wrapper" id="app"> <router-view></router-view> //using Vue ...

Enable the parsing of special characters in Angular from a URL

Here is a URL with special characters: http://localhost:4200/auth/verify-checking/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="59663c34383035643230383d2b606a6e6b686d6e6e193e34383035773a3634">[email protected]</a> ...

Distributing actions within stores with namespaces (Vuex/Nuxt)

I'm encountering an issue with accessing actions in namespaced stores within a Nuxt SPA. For example, let's consider a store file named "example.js" located in the store directory: import Vuex from "vuex"; const createStore = ...

Mapbox GL JS stops displaying layers once a specific zoom level or distance threshold is reached

My map is using mapbox-gl and consists of only two layers: a marker and a circle that is centered on a specific point. The distance is dynamic, based on a predefined distance in meters. The issue I'm facing is that as I zoom in and move away from the ...

What is the most effective method to exhibit every element within a content wrapper at a specific interval of time?

I am looking for a way to display each div within the content-wrapper after a specific time interval. Currently, I am using individual classes like el1, el2, el3, ... to accomplish this task. However, when dealing with content-wrappers containing multipl ...

Retrieve the 90 days leading up to the current date using JavaScript

I've been searching for a way to create an array of the 90 days before today, but I haven't found a solution on StackOverflow or Google. const now = new Date(); const daysBefore = now.setDate(priorDate.getDate() - 90); The result I'm looki ...