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

click event to activate delayed function in dropdown

Within the li element, there is an onclick function with a data-toggle="dropdown" attribute. The issue at hand is that my function isn't triggered when I click once, but interestingly it works after clicking twice. I invoke this function to ensure th ...

Unable to include any additional Angular Module

While using Jhipster v3.9.1, I attempted to add a module to my project but encountered some difficulties. Specifically, I wanted to incorporate the module found at . To achieve this, I ran the command bower install angular-mass-autocomplete --save followed ...

The initial render of Keen-slider in NextJS can sometimes encounter difficulties when using server-side rendering

While incorporating the keen-slider library v5.4.0 into my nextJS project with TypeScript, I encountered a peculiar issue. The error arises when the keen-slider is initially loaded for the first time, resulting in mismatched transform types causing items ...

Implement a Codeigniter model that utilizes JavaScript to insert an ID

Is there a way to retrieve the productid value in PHP code? function getunitstock(){ var productid = document.getElementById('product').value <?php $prodbyid = $this->pos_model->get_productbyid(+productid+)?> document. ...

The file 'index.js' does not have a default export

Stepping into the world of MERN development, I embarked on a journey to construct a learning management system based on an outdated tutorial. To my dismay, I encountered the following error: > ..\server\middlewares\index.js:1 > import ...

Importing modules in Node can be done after the code has been executed, or through ESM Dynamic

I am currently working on a project in nodejs and express, and I am facing an issue where I need to execute certain code before importing modules. The app is already set up to use import for modules instead of require, and changing this setting is not an o ...

Loop stops after completing one iteration

I am currently working on a program that automatically generates ASCII text based on input numbers. Essentially, when a number is provided as input to the function, it will be displayed as magnified ASCII text. For example, an input of 0123456789 would gen ...

Setting up vue-resource root and authentication configuration

Currently, I am reviewing the documentation for vue-resource that outlines how to configure it: https://github.com/vuejs/vue-resource/blob/master/docs/config.md The documentation specifies setting headers with a common authorization value: Vue.http.hea ...

Experiencing issues with exporting <SVG> file due to corruption

I received some downvotes on my previous post, and I'm not sure why. My question was clear, and I provided a lot of information. Let's give it another shot. My issue is with exporting <SVG> files from an HTML document. When I try to open t ...

Guide to Displaying HTTP POST Request Response on Pug Template

Whenever a user interacts with the form, I initiate an HTTP POST request to the database server. Subsequently, the database server sends a POST request back to the user's server. The issue I am facing is the inability to display this database result ...

AngularJS Data table: unresponsive feature not functioning

I'm currently utilizing the angular-datatables plugin along with the responsive table feature, but unfortunately it's not functioning as expected: the table appears without the responsive design. Module: (function () { 'use strict&apos ...

forward to a different link following the backend script execution

I am facing a challenge with the signup.php page which includes a Facebook login button. The structure of the page is as follows: <?php if(!isset($_SESSION['logged_in'])) { echo '<div id="results">'; echo '<!-- ...

What is the best way to make an ajax commenting system function from a separate directory?

I am facing an issue with implementing an ajax commenting system on my website. When I place all the code from the /comment directory directly in the root, everything works fine and the commenting system functions as expected on new pages. However, when I ...

Execute the function once the AngularJS binding has been completed

I am working on a basic app that utilizes Angular to perform an HTTP GET request. The data returned is then assigned to an array and displayed on the DOM using ng-repeat. My goal is to execute some code that manipulates this DOM after it has been fully ren ...

Is there a way to activate the autoplay feature for this?

I'm really new to Jquery and most of this code isn't mine, I'm just using it as a learning tool for creating sliders. If someone could give me some guidance on how to make this slider work automatically when the page loads, that would be gre ...

How about rejuvenating a Div with some PHP magic inside?

My goal is to automatically update a div every x seconds by using the following code: The div only contains a small PHP timezone code. This is the code snippet I am implementing: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/ li ...

Accessing Next and Previous Elements Dynamically in TypeScript from a Dictionary or Array

I am new to Angular and currently working on an Angular 5 application. I have a task that involves retrieving the next or previous item from a dictionary (model) for navigation purposes. After researching several articles, I have devised the following solu ...

Gridsome server-side rendering encounters issues with Auth0 authentication when the window object is not defined

After successfully following the Auth0 Vuejs tutorial with Gridsome during development, I encountered a problem when trying to build using gridsome build. The build failed because window was undefined in a server context. I discovered some issues in the A ...

Comparing Buffer and Uint8Array in Node.js

Exploring the documentation for the fs module 1, we come across the following regarding the writeFile method: const data = new Uint8Array(Buffer.from('Hello Node.js')); Further in the documentation 2, it states: With TypedArray now available, ...

What are the best ways to implement advanced data filtering in JavaScript?

Is there a way to improve the filtering of data in the ngx-datatable? Currently, I have a filter that only works for the "Name" column. How can I adjust it to filter data from other columns like "id" or "phone" as well? filt ...