Angular $watch is not functioning as expected

I've encountered an issue while trying to monitor a variable that I set in my service. Despite changing the value in the controller, the watch event fails to trigger.

Below is the code snippet:

var app = angular.module("Test", []);
app.service("testService", TestService);
app.controller("testController", TestController);

function TestService()
{
    var self = this;
    self.Message = "1";
}

TestController.$inject =["$scope", "testService"];
function TestController($scope, testService)
{
    var self = this;
    self.Message = testService.Message;
    $scope.Message = self.Message;

    $scope.$watch("Message", onMessageChange, true)
    self.click = function()
    {
        testService.Message = "2";        
    }

    function onMessageChange(oldVal, newVal)
    {
        self.Message = newVal;
    }
}

As for the HTML:

<!DOCTYPE html>
<html >
    <head>
        <title>Test</title>

     <script src=".\angular.js"></script>    
     <script src=".\test.js"></script>    
    </head>
    <body ng-app="Test">
   <div  ng-controller="testController as ctrl">
    <button  ng-click="ctrl.click()"> Click </button>
    <span> Message: {{ctrl.Message}}</span>
</div>
    </body>
</html>

What could be causing this malfunction? Any insights on what might be incorrect?

Answer №1

To monitor your service variable effectively, follow this method:

$scope.$watch(function() { return updatedService.Data;}, updateOnChange, true)

Don't forget to make adjustments for old and new values:

function updateOnChange(newValue, oldValue)
{
    self.Data = newValue;
}

Previously, the code only observed your $scope.Message instead of the service variable.

$scope.$watch("Message", onMessageChange, true)

This would only be triggered when the variable is altered in your click function, like so:

self.click = function()
{
    $scope.Message = "2";        
}

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

Tips for preserving filters or results following filtering with DataTables' searchPane

Utilizing the searchPane extension of DT, which is an R interface to the DataTables library. When constructing a dataTable with a searchPane, the code would appear as follows: library(DT) datatable( iris, options = list(dom = 'Pfrtip', ...

multiple pieces of data from the controller

I am attempting to display additional data from the controller in the same item. When I try to add another condition in ng-repeat like "file in fileno & filedet in descript & status in statusno", the item does not appear. Controller .controller('cas ...

Secure HTML / CSS for JavaScript? I am unable to modify certain attributes during runtime

Due to ongoing discussions about blog colors for business purposes, we are looking to provide users with a "tool" (for those who are tech-savvy) to experiment with colors themselves. Our blog is a basic Wordpress site with various plugins (such as Google ...

Revamping FullCalendar: Strategies for refreshing or initializing FullCalendar anew or efficiently adding multiple events at once

I attempted to batch add new events to the calendar but failed to find a convenient method to do so. As a result, I decided to reinitialize the view with a new events array. Here's what I tried: var events = [ { title: 'Conference&ap ...

How can I transfer objects containing state information, such as connections, in ExpressJS?

This question delves into the architectural aspects of a project using ExpressJS, Angular, and Socket.io. The challenge at hand is how to persist the socket.io instantiation so that other parts of the project can utilize it effectively. Let's dive in ...

Issue: An ongoing backoff operation is currently underway when attempting to retrieve data from Firebase in a React application

Hello everyone, I've recently delved into electron js and attempted to establish a connection with firebase using react in typescript. Unfortunately, I encountered an error while trying to read data from firebase. I followed the approach outlined in ...

Watch F4V content using JWplayer on your iOS device

Having trouble playing a f4v file using JWplayer on an iOS device (specifically an iPhone). Check out the player setup code below: jwplayer(player).setup({ file: file, primary: "flash", autostart: false, aspectratio: "16:9", autostart: ...

Ensuring that a canvas remains centered and completely visible within its parent element while zooming in React

Currently, I am developing a straightforward PowerPoint creator using React. In this project, I have integrated a zoom feature for a canvas element. The principle is that the canvas should resize based on a scale factor. However, there seems to be an issue ...

The code for implementing the "Read More" feature is not functioning as intended

I have been experiencing an issue with the implementation of the "read more" feature on my website. Although the code seems to be functioning properly, it only works after pressing the read more button twice. This particular code is designed to detect the ...

Having trouble with GSAP CDN not functioning properly in your JavaScript or HTML document?

After watching a tutorial on YouTube by Gary Simon, I attempted to animate text using GSAP. Despite following the instructions meticulously and copying the CDN for GSAP and CSSRulePlugin just like him, nothing seems to be happening. Even setting my border ...

Auto-filling a form with the selected 'id' in Django using JavaScript or AJAX

I am a novice and I want the form to be autofilled when I select a vehicle ID from the template. Here are my models. class Fuel(models.Model): vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE) previous_km = models.IntegerField(blank=False, nul ...

Can you explain the contrast between body.onunload and body.onbeforeunload?

Similar Question: Explaining the distinction between onbeforeunload and onunload Tell me, what sets apart body.onunload from body.onbeforeunload events? From what I've gathered, I should be able to apply onunload and onbeforeunload to any HTML el ...

Sharing JSON data with Angular 1 (Ionic) components: a comprehensive guide

Currently, I am working with the Ionic framework and facing an issue with passing data between templates through a click action. The data is fetched using $http.get method within a Service, and both templates (or views) are managed by a common 'MainCo ...

Data tables failing to display accurate data

I have implemented Datatable for a table with eight identical columns and three columns that vary based on the selected radio button. The table is dynamically filled using an ajax call to a python function and the returned data is added to the table body. ...

Getting the badge value of a button in Angular JS is a simple process that involves accessing

How can I retrieve the badge value of a Button? This badge represents data-text-as-pseudo-element and I am new to Angular. Can someone guide me on how to achieve this? <style type="text/css">[data-text-as-pseudo-element]::before { content: ...

I need to set a JavaScript variable to an HTML element within a JavaScript function

I am attempting to insert a JavaScript variable value into an HTML element within a JavaScript function, but I am encountering issues. Below is the code snippet: window.onload = function() { var image=document.getElementById('img').value; ...

Window displaying multiple product options

Having an issue creating modal windows for multiple products, where only the last product is being displayed in each window. Attempted to assign id identifiers, but faced a problem where only the modal window of the first product functions correctly. wi ...

I added an onClick event to an SVG image, however, I am struggling to get the event to execute a jQuery if/else statement

I've been working on creating an SVG map of the US, and I'm almost finished. The final step involves implementing a simple if-else statement to prompt users for the name of the state when they click on it. My goal is to fill the state green if th ...

Error: Unable to change image -- TypeError: Cannot assign value to null property 'src'

As I work my way through the textbook for one of my classes, I am practicing by building an image swapping page. The concept is simple - clicking on a thumbnail swaps out the main image and enlarges it as if it were linking to another web page. Despite fol ...

Troubles with showcasing icons on a website

I need some help with a minor issue that I'm stuck on. I'm trying to display an information icon that, when clicked, opens a pdf. The strange thing is that the icon doesn't show up on the page even though it exists on the server. However, wh ...