Watching for changes triggers the promise's "then" function for an array but not for a singular value

As a beginner in the world of Angular, I am encountering a strange issue that has me puzzled. My controller has two scope properties - "sentences" and "countVal" which are displayed on my HTML page.

I use a factory called "ModelState" to hold my data, which is populated by the service "UpdatingService."

The problem arises when I try to push data into ModelState.values using "ModelState.values.push(data);" The array length increases to one, but the count value remains unchanged. Additionally, the $watch function in TestCtrl does not log anything to the console. I know there must be something wrong with what I'm doing, but I can't seem to pinpoint it. Here is my HTML code (with the script inline). Thank you in advance for any help.

<!doctype>
<html ng-app="testApp">

<head>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.15/angular.js"></script>
</head>

<body ng-controller="TestCtrl">

<p>Array length : {{ sentences.length }}</p>
<p>Count value  : {{ countVal }}</p>
<br>

</body>

<script>
var testApp = angular.module('testApp', []);

testApp.controller('TestCtrl', function($scope, ModelState, UpdatingService) {

  $scope.sentences = ModelState.values;
  $scope.countVal  = ModelState.countVal;

  $scope.$watch("countVal", function(newValue, oldValue){
    console.log(newValue,"  ",oldValue);
  }, true);
});

testApp.factory('ModelState', function(){
  return {
    values : [],
    countVal : 0
  };
});

testApp.service("UpdatingService", function($http, $timeout, ModelState, $q){
   var service = {

    getData:function(){
      var promise = $http.get("http://baconipsum.com/api/?type=meat-and-filler");

      promise.success(function(data){
        ModelState.values.push(data);
        ModelState.countVal++;
      });

      return promise;
    }
  };

  service.getData();

  return service;
});

</script>

</html>

Answer №1

When you add the following code in your controller:

$scope.sentences = ModelState.values;
$scope.countVal  = ModelState.countVal;

You are creating a reference for the sentences array - now both ModelState and $scope point to the same instance of the Array.

On the other hand, you are assigning a value to the countVal property - making ModelState and $scope refer to 2 different instances of Number.

Therefore, when you push a new item to sentences, the change in its length is reflected in the view, but $scope.countVal remains unchanged because you only modified the property of ModelState.countVal.

To address this issue, one solution is to simply assign $scope.ModelState = ModelState and directly access its properties in the view:

<p>Array length : {{ ModelState.sentences.length }}</p>
<p>Count value  : {{ ModelState.countVal }}</p>

Another approach would be to utilize scope methods to retrieve ModelState values like this:

$scope.sentenecesLength = function(){
  return ModelState.sentences.length;
};
$scope.countVal = function(){
  return ModelState.countVal;
};

<p>Array length : {{ sentenecesLength() }}</p>
<p>Count value  : {{ countVal() }}</p>

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

How can aoColumnDefs be configured in jQuery DataTable without the need to instantiate a new DataTable object?

When it comes to setting column names, I am familiar with using the following method: var table = $('#'+String(response.chartID[i])).DataTable({ stateSave: true, aoColumnDefs: aryJS ...

The onClick function within the .map function is continuously triggered

I am encountering an issue with my code where a Dialog confirmation prompt from Material UI keeps getting called unexpectedly. The problem seems to arise when I add a value to the function that is triggered by a button click within a loop of an array usi ...

Codepen for showcasing your Javascript and Jquery skills

I'm having a bit of trouble with the .getjson function. I've been working on retrieving data from a Wikipedia API using .getjson, and while everything seems to be working fine, there's a peculiar issue when I try to find the length of an arr ...

What is the best way to extract data from a JavaScript object in C++?

I have integrated an IE ActiveX control within my C++ (MFC) application. This embedded IE contains a JavaScript method that sends data back to my C++ application using the following simplified JavaScript code: function passDataTocpp() { return {ke ...

Iterate through each page to gather product links and store them into a unified array

I have managed to obtain some code with assistance, and you can find it at the following link HERE. While the code works effectively in theory, I am encountering an issue where it is returning links and arrays for each page individually. What I want is for ...

What is the best way to target an element that does not exist yet?

I have a project for managing a todo list. When I click an "add" button, it creates a div element with another "add" button inside it. That part is easy. But now, I want to select that inner button so that I can use it to add a text input form inside the n ...

Exploring the World of Regex Character Sets and Their Contents

Currently, I am developing a basic sanitizer for string input in Node (express): After looking at various plugins and libraries, I found that most of them are either too complex or heavy. Therefore, I made the decision to create some simple sanitizing fun ...

HTML steps for smooth scrolling to the top and bottom of a list

My HTML contains a vertical list with top and bottom arrows positioned nearby. I am looking to implement a function where clicking on the top arrow will move the list up gradually, and clicking on the bottom arrow will move the list down step by step. Belo ...

What is the process for including a custom Jasmine matcher definition in Typescript?

I've been searching around for information on creating custom Jasmine matchers using TypeScript and it seems like a common issue. However, none of the solutions I've come across have worked for me. My setup includes: { "typescript": "2.3.2", ...

Hover and Click Card Turning

My card can both hover and click, but there seems to be a small glitch. After clicking on the card and then moving the cursor away from the front, the hover effect doesn't work correctly. It immediately flips back to the front side. The hover effect ...

Having trouble with log4js-node in Node.js not recording logs to file?

Not a expert in nodes, this is my first time using log4js-node. I am attempting to log my ERROR logs and any console logs to a file named log_file.log using log4js on a nodejs server running Express. Below is my configuration file: { "replaceConsole": ...

Using AngularJS to bind $scope in the run function

Being new to AngularJS, I encountered a common functionality across all controllers. To handle this, I placed the code in the run method. This particular code is responsible for redirecting to another page when a certain condition is met. However, when usi ...

Prevent mdDialog from automatically resizing to fit content upon opening

I am currently using a material design $mdDialog that includes a search bar. I've noticed that when the search results are shorter (with fewer characters), the dialog automatically shrinks to fit the width. Is there a method to set the initial width o ...

What is the best way to supply arguments to a generic handler function?

How can I send parameters to a generic handler in Asp.net using JavaScript/jQuery? I am working on a jQuery plugin called ajaxfileupload that utilizes a generic Handler. I need to pass certain arguments from the page using jQuery or JavaScript, such as Dy ...

Enhance text area size using AngularJS

Looking to dynamically adjust the number of rows in a text area on focus and blur events, as well as show a hidden div layer upon focus. Currently achieving this with the following code: <textarea class="form-control" rows="1" placeholder="Please enter ...

Develop a personalized event using JavaScript and activate it

I have encountered a problem with a Google ad that expands on click and closes when the close button is hit. However, due to changing conditions, I now need it to expand first and then automatically close after a certain time. Additionally, every time it e ...

JavaScript appending checkboxes to a list not functioning as expected

I have not been using jQuery, JavaScript, and HTML to create a list of products. The task I am working on now is the ability to select multiple items from this list. Currently, the HTML list is dynamically populated with <li> elements using JavaScri ...

Alter certain terms in HTML and update background using JavaScript

I want to create a filter that replaces inappropriate words and changes the background color using JavaScript. Here is what I have so far: $(document).ready(function () { $('body').html(function(i, v) { return v.replace(/bad/g, &apos ...

Display HTML content within designated fixed-column sizes

Looking to divide the content of an HTML file into multiple fixed size columns, both in terms of height and width, then display it in a Webview. I attempted employing the CSS properties mentioned below, but couldn't get it to function as desired. -we ...

We apologize, but the module you are looking for cannot be found: Unable to locate 'fs'

Trying to create a new MDX blog website using Next.js 13 with the latest app router, but encountering an error message saying "Module not found: Can't resolve 'fs'". It was working fine in Next.js 12 and pages directory, but not in the lates ...