Monitoring changes to a service object in AngularJS

I've experimented with various examples involving the watch function, but I can't seem to get it to function correctly. The scenario involves monitoring a service that contains an array of objects, where each object includes an array of arrays. My goal is to monitor changes within these arrays of arrays.

JSON

 [{
    "name": "Chantal Hamlet - Green Castle Homes",
    "subId": "10223",
    "bldId": "13551",
    "data": [
        [179900, 1386],
        [214900, 1440],
        [194500, 1496],
        [217900, 1504],
        [189900, 1542],
        [184900, 1546],
        [192500, 1570],
        [189900, 1576],
        [191900, 1598],
        [204900, 1626],
        [219900, 1651],
        [212900, 1704],
        [214900, 1787],
        [219900, 1837],
        [224900, 1857]
    ]
 }, {
     "name": "Ella Sea Condos - Sahnow Construction",
     "subId": "9761",
     "bldId": "27380",
     "data": [
         [199900, 1500]
     ]
 }]

Watch function

$scope.$watchCollection(function () {
    return chartService.series
},
function (rawData) {
    $scope.seriesData = rawData;
});

Service

chart.factory('chartService', function () {
return {
    getSeries: function () {
       return this.series;
    },
    setSeries: function (series) {
        this.series = series;
    },

Answer №1

One issue arises when your setSeries function modifies the watched object.

Imagine this:

chartService.series = ObjectA

Watch ObjectA

chartService.series = ObjectB

ObjectA remains unchanged.

To resolve this, encase it in a stable larger object.

angular.module('chartModule', [])
.controller("chartController", ['$scope', 'chartService',
  function($scope, chartService) {
    $scope.seriesData = chartService.seriesContainer;


    $scope.changeData = function() {
      chartService.seriesContainer.series = [{
        "name": "New Name",
      }];
    }
  }
]).factory('chartService', function() {
  return {
    getSeries: function() {
      return this.series;
    },
    setSeries: function(series) {
      this.series = series;
    },
    seriesContainer: {
      series: [{
        "name": "Chantal Hamlet - Green Castle Homes",
      }]
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="chartModule">
  <div ng-controller="chartController">
    {{seriesData.series[0].name}}
    <button ng-click="changeData()">Change Data</button>
  </div>
</body>

By utilizing a wrapper, you can eliminate the need for a watch as it will update automatically.

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

Is it possible for a PHP form to generate new values based on user input after being submitted?

After a user fills out and submits a form, their inputs are sent over using POST to a specified .php page. The question arises: can buttons or radio checks on the same page perform different operations on those inputs depending on which one is clicked? It ...

Efficiently load numpy arrays from a text file

Seeking a solution to efficiently read a matrix from a text file into a numpy array without unnecessary copying. Here is the format of the matrix: 3 1 -1 6 5 9 7 0 -7 0 -5 -5 3 -7 -2 4 3 -2 -9 -5 6 6 -2 -9 9 -7 ...

Personalized selection in React with list filtering

I have created a custom dropdown menu and I am facing an issue. When a user selects an element from the dropdown, I want that item to be removed from the list so it does not show up again. Here's how it currently looks when I click on the select for t ...

Sending data from jQuery to an AngularJS function is a common task that can be accomplished in

In my Controller, I have a function that saves the ID of an SVG path into an array when a specific part of the image.svg is clicked. $(document).ready(function(){ var arrayCuerpo=[]; $('.SaveBody').on("click", function() { ...

Retrieve the computed style of a cloned element that has not yet been appended to the document

I am dealing with an HTML page that looks like this: <div id="cloneDiv"> <h1> <a href="">ASUS Vivotab Smart Black Office 2013 H&S ME400C-C2-BK 10.1-Inch 64GB Tablet (Black)</a> </h1> <di ...

Understanding the evaluation of functions in Node.js

As a beginner in Nodejs and Expressjs, I have just started working on building custom applications. However, I am facing some challenges in understanding a particular piece of code and how it functions. Any clarification or suggestion for an alternative ap ...

Execute functions in a random order

My array contains a series of functions and is structured as shown below: var all_questions = [ show_question(1, 1), show_question(2, 1), show_question(3, 1), ]; I'm interested in executing those functions within the array in a random or ...

ng-style not responding quickly to changes

Having trouble with my progress bar <div class="progress progress-striped" ng-class"{active: file.isUploading()}"> <div class="progress bar" role="progressbar" ng-style="{'width' : (file.sizeUploaded() / file.size * 100) + '%&a ...

"Is it possible to access variables declared in the main app.js file from separate route files in Node.js Express 2.5.5 and if so

Recently, I've started using the latest version of Express (2.5.5) which now automatically creates a ./routes directory in addition to ./views and ./public In the routes directory, there is an index.js file that includes: /* * GET home page. */ e ...

What is the correct way to test setInterval() statements within Angular?

Here is a simple code snippet I am working on: public async authenticate(username: string, password: string) { const authenticationResponse = await this.dataProvider.authenticate(username, password); if (authenticationResponse.result.code == 0) { ...

What causes the DOM's appendChild() to trigger on('load', ...) while jQuery's append() does not fire?

I have two snippets of code that I am working with: $(document).ready(function() { document.head.appendChild( $('<script />').attr('src', 'source.js').on('load', function() { ... ...

Extract elements from a String Array that are not in the List

Is there a way to efficiently remove all elements from List X that exist in List Y? I have a String Array x and a List y, and I need to find the quickest method to achieve this. For example: X: 1) "aaa.bbb.ccc" 2) "ddd.eee.fff" 3) "ggg.hhh.jjj" Y: 1) "bb ...

What is the best way to share my array with different functions?

In my program, I have an array that is declared within the main() function. I want to be able to access this array in a different function that is called from main(). What is the most effective way to make this array accessible to the other function? I e ...

Issue with JQuery UI buttonset functionality when using radio buttons with the runat="server" attribute assigned

I'm currently working on a demo application where I need to use radio buttons as buttons. To achieve this, I'm utilizing the JQuery UI buttonset widget. Everything was functioning correctly until I decided to add the attribute runat="server" in o ...

Having issues with my jQuery getJSON request. It's returning an empty response even though

I have been struggling to find a solution to this particular issue with no luck... Here is the jQuery getJSON request that I am working on: $.getJSON("http://localhost:8080/context/json/removeEntity.html", { contentId : 1, entIndex : entityIndex ...

What is the process for adding elements to an array, then sorting it in JavaScript and returning the sorted array

Having an issue with my code snippet below, My goal is to insert a new record at the beginning of the array and then sort it based on the label. However, I'm encountering an unexpected outcome where the array turns out empty. const array = [{id: &apos ...

Tips for obtaining response headers

Currently, I am utilizing Angular version 15.0 and retrieving a list of items from the backend (ASP.NET Core 5) with an additional item attached to the header. The GET method in the client-side service is as follows: /** GET Paged commodities from the s ...

Java modal dialog box with Selenium WebDriver

During my form testing, I encountered a javascript alert in my web app notifying users to fill in missing data if needed data is not typed. The problem arises when using selenium to handle this alert, as an exception occurs when trying to submit the partia ...

Issue: When calling setState(...), you must provide either an object containing the state variables to update or a function that will return an object with the updated

Encountering an error in the else section with this.state.incorrect + 1 and this.state.correct + 1 I've come across a similar issue that wasn't resolved by visiting this link: React Native: setState(...): takes an object of state variables to up ...

Navigating with nodeJS

Currently, I am in the process of learning how to create a Node.js project. My latest endeavor involved following a tutorial to develop a chat application. However, it seems like there is an issue with the routing between the server side and client side. ...