Observing data within an AngularJS service

I am currently working with a service called sharedData and a controller named HostController. My goal is to have the HostController monitor the saveDataObj variable within the sharedData service, and then update the value of host.dataOut, which will be reflected in the view as an ngModel attribute.

The challenge I'm facing is that I am unsure about how to effectively use the $watch function. Ideally, I want the value of host.dataOut to be automatically updated whenever there is a change in the saveDataObj variable in the sharedData service (or whenever the setData method is called).

Upon running the following code snippet, I receive the following message in the console:

 sharedData.getData(): Object { }

This output is expected during initialization. However, when I trigger the setData method from another controller to modify the value of saveDataObj, no new logs are displayed in the console.

Can someone please point out what mistake I might be making?

angular.module('app', [])

.factory('sharedData',function(){
  var saveDataObj = {};
  return {
    getData: function(){
      return saveDataObj;
    },
    setData: function(data){
      saveDataObj = data;
    }
  };
})

.controller('HostController',['$scope','sharedData',function($scope,sharedData){
  $scope.sharedData = sharedData;
  var host = this;
  host.dataOut = {};
  $scope.$watch(
    'sharedData.getData()',
    function handleDataChange(newValue,oldValue) {
      console.log("sharedData.getData():",newValue);
      host.dataOut = newValue;
    }
  );
}])

Answer №1

.controller('HostController',['$scope','sharedData',function($scope,sharedData){
  $scope.sharedData = sharedData;
  var controller = this;
  controller.outputData = {};
  $scope.remoteData = sharedData.getData(); //local variable
  $scope.$watch('remoteData', function(currentValue, previousValue) {
      console.log("sharedData.getData():",currentValue);
      controller.outputData = currentValue;
    }
  );
}]);

Wishing you find this information useful!

Answer №2

Answer from the original poster:

The issue I encountered was not related to trying to $watch something in a service, but rather attempting to $watch an Object. In order to achieve this, I needed to set the third parameter of $watch, objectEquality, to true.

$scope.$watch(
  'sharedData.getData()',
  function handleDataChange(newValue,oldValue) {
    console.log( "sharedData.getData():", newValue );
  },
  true
);

https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$watch

I have chosen to mark this as the best answer because I have a tendency towards narcissism.

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

Find a way to incorporate social media features into a web application that functions intermittently

Currently, I am in the process of developing a social media app and working on integrating a search feature to enable users to find friends. The code I have below seems to be functional at times but not consistent (quite frustrating!) The issue seems to st ...

Access-Control-Allow-Origin does not permit the origin null

I've been searching for an answer to this question, but I haven't found a suitable one yet. let xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(){ if(xhr.readyState === 4 && xhr.status === 200){ let response = r ...

Concealing Popover with internal click

I am currently implementing Vue-PopperJS in my project, following the setup provided on the linked page with a few modifications: <template> <Popper ref="popover" trigger="clickToToggle" :options="{ pla ...

Issue with button events not being triggered while working with dynamically created classes

I am facing an issue with three plus (+) buttons that are next to three separate tables built using DataTables. The problem arises because all the plus buttons were created in one location with DataTables, resulting in them being assigned the same classes ...

Updating HTML images in real-time using a combination of Flask and Ajax

I am facing a situation similar to the one discussed in this thread: Flask+AJAX+Jquery+JINJA to dynamically update HTML Table. However, I am struggling to adapt the solution to suit my specific requirements. My objective is to automatically update the imag ...

What is the method for retrieving a child element using its ID in JavaScript?

Below is the HTML code I am working with: <div id="note"> <textarea id="textid" class="textclass">Text</textarea> </div> I am trying to retrieve the textarea element without using document.getElementById("textid"). This is what I ...

The data binding does not function properly when using two nested ng-repeat directives

Unfortunately, there seems to be an issue with data binding when dealing with nested ng-repeat loops containing textboxes. While the first level hierarchy with prop functions correctly, the second level down with sensor does not properly bind the values ba ...

The feature to disable swiping with SwipeEnabled set to false seems to be

I am encountering an issue with react-navigation 5 in my react-native project. I am trying to disable drawer swipes while still allowing the user to close the drawer by clicking outside of it. I have researched this property in the react-navigation documen ...

Leveraging D3.js in combination with Total.js and node.js

I have been attempting to utilize total.js in conjunction with D3 for creating a tree visualization. However, I am encountering issues when trying to download D3. This is what I do: npm install D3 Upon running the above command, I receive the following e ...

Preventing jQuery plugin from overriding default settings

I have created a jQuery plugin using the nested namespace pattern, inspired by the design template found in Addy Osmani's book. The plugin is a simple gallery and everything seems to be functioning correctly. However, I am facing an issue when attemp ...

Is it possible to prevent users from clearing data in an Android application when using Ionic framework?

Currently, I am developing an app using the Ionic framework. The data is being stored on the mobile device via SQLite, but there is a concern that users can easily clear this data by clicking on the "clear data" button in the application info settings. The ...

ReactJS aligns buttons to the right

I have been attempting to align a button to the far right without success. Here is what I have tried: <Button variant="contained" style={{display: 'flex', justifyContent: 'right'}} color="primary" className="float-right" onClick={ ...

Monitoring an Angular form for changes in its $dirty state can provide valuable insights into performance

I have a question about my Angular application. I am dynamically setting placeholders in my form based on the time of day using code inside the controller. Is there a way to clear all placeholders when a user starts typing into any field of the form? I h ...

Develop a revolutionary web tool integrating Node.js, MongoDb, and D3.js for unparalleled efficiency and functionality

I am exploring the creation of a web application that will showcase data gathered from various websites. To achieve this, my plan involves automating the process of data collection through web scraping. After collecting the data from these sites, I will fo ...

Why are the radio buttons not aligned with the text in the center?

Currently, I am in the process of building a form that includes radio buttons. However, I've encountered an issue where the text next to the radio buttons appears on a different level than the buttons themselves. How can I go about fixing this partic ...

Steps for setting up i18nextStart by including the i

I am working on developing a multilingual app using the i18next package. Unfortunately, I am experiencing issues with the functionality of the package. Below is an example of the i18next file I have been using: import i18n from "i18next"; impor ...

Animating Text Changes with JavaScript and jQuery

In my HTML, I have an input type="text" element and I want to attach an event handler that triggers when the text is changed. The issue arises because this input's value is dynamically updated by another JavaScript function, causing the event handler ...

Build a photo carousel similar to a YouTube channel

Is there a way to create an image slider similar to the one on YouTube channels? I've noticed that when there are multiple videos on a channel, YouTube displays them in a slider with back and forth buttons to navigate through the videos that aren&apos ...

Dynamically Loading CSS files in a JQuery plugin using a Conditional Test

I'm trying to figure out the optimal way to dynamically load certain files based on specific conditions. Currently, I am loading three CSS files and two javascript files like this: <link href="core.min.css" rel="stylesheet" type="text/css"> & ...

Accessing my data within the controller in Angular

I somehow managed to display all my data in the view without having a reference to it in the controller. Initially, I thought my data would be in $scope or this, but I can't seem to locate it anywhere. This is how my view looks: <script src="con ...