Angular monitoring problem

Today marks my first attempt at utilizing Angular's watch function, but I'm having trouble getting it to function properly. Within my codebase, there exists a service named apiService, housing a variable called myFile. By injecting this service into my controller, I aim to monitor any changes in the value of apiService.myFile. Regrettably, it seems that the watch function only triggers upon initial webpage load and fails to react when the apiService.myFile variable undergoes a change. Below is the snippet showcasing the watch implementation:

$scope.$watch(function(){return apiService.myFile}, function (newVal, oldVal, scope) {
    console.log("service changed: "+newVal +" : "+oldVal+" : "+ scope);
});

Could you shed some light on why it isn't responding to changes in myFile?

UPDATE 1: Here's how I update the value of apiService.myFile within the service:

ApiService.prototype.uploadFile = function(fileContent) {
    $.ajax({
        url: "/space_uploadFile/",
        type: "POST",
        dataType: "json",
        data: {
            fileContent: fileContent
        },

        contentType: "application/json",
        cache: false,
        timeout: 5000,
        complete: function() {
          //called when complete
          console.log('process complete');
        },
        success: function(data) {
            this.myFile =data;
            console.log("this.myFile: "+this.myFile);
            console.log('process success');
       },
        error: function() {
          console.log('process error');
        },
      });

};

Answer №1

After testing it in a plunkr myself, I found that this solution works:

Pro tip: next time, provide a plunkr example to help us better understand and troubleshoot your issue (e.g. typo).

var app = angular.module('app', []);

app.controller('mainController', function($scope, apiService) {

  $scope.changeValue = function() {
    apiService.myFile += "!";
  };

  $scope.$watch(function(){return apiService.myFile}, function (newVal, oldVal, scope) {
    console.log("service changed: "+newVal +" : "+oldVal+" : "+ scope);
    $scope.someValue = newVal;
  });
});

app.service('apiService', function() {
  this.myFile = "Test";
});

Here is the corresponding HTML code:

<body ng-controller="mainController">
  <h1>Hello Plunker!</h1>
  {{someValue}}
  <button ng-click="changeValue()">Click</button>
</body>

https://plnkr.co/edit/DpDCulalK1pZ8J0ykh2Z?p=preview

On a side note: The $watch part was directly from your question and it worked flawlessly for me.

Edit: It turns out that the OP was using $.ajax for ajax calls and updating the value outside the Angular context in the success handler. Therefore, no digest cycle was triggered. To resolve this, consider using Angular's $http service or finding an alternative approach.

var self = this;
self.$http.post("/space_uploadFile/",
{ fileContent: fileContent },
{ 
    cache: false,
    timeout: 5000
})
.then(function (data) {
    self.myFile = data;
    console.log("self.myFile: " + self.myFile);
    console.log('process success');
},
function () {
    console.log('process error');
});

Edit2: Additionally, the OP was attempting to access variables on the controller using this within the success handler, which does not work as intended. In the provided sample above, I used the self pattern to address this issue.

Answer №2

Here is a common syntax I am familiar with:

scope.$watch('name', function(newValue, oldValue) {
  scope.counter = scope.counter + 1;
});

The property name being watched is typically referred to as myFile in this scenario.

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

What is the best way to remove existing values and update with new values from a JSON using JavaScript?

The following is an excerpt of html code: <div id="prt"> <select name="selectPrt" class="span12" onchange="sta_callPRT();"> <option value="noPrt">Choose one vehicle.</option> <option value="prt1"> ...

Optimizing jQuery Dialog for Different Window Sizes

I am currently developing a responsive website and facing a challenge. I need to implement a popup for window sizes smaller than 480px, but on desktop screens, the content should be visible without being inside the popup. I want to avoid duplicating the co ...

What considerations need to be made for testing a component that relies on other components as well?

When creating tests for a web-component (parent) that utilizes other web-components (children), should the parent component's tests also cover to ensure proper rendering/configuration of the children components? For instance, let's consider a co ...

Encountering error when using require() with Firebase in Express

I am facing an issue with my Express application while attempting to connect it to Firebase. Currently, my console is showing an error message: C:\Users\Tyler\Desktop\Dev\food-bank\app.cjs:19 const firebase = initializeApp(fi ...

The Owl carousel's autoplay feature seems to be set at a fixed speed of 5

I've been attempting to adjust the autoplay speed on an owl carousel (specifically using owl carousel 1), but no matter what integer I add after autoplay:, it remains stuck at 5 seconds. The website, which is currently broken, suggests that adding a n ...

The AngularJS plugin "chosen" is experiencing issues with the "chosen:updated" feature, despite functioning

After successfully integrating the selected plugin into my AngularJS app, my app.js file now has the following code: myApp.directive('chosen', function() { var linker = function (scope, element, attr) { scope.$watch('countriesL ...

Having trouble adding/removing/toggling an element class within a Vue directive?

A successful demonstration can be found at: https://jsfiddle.net/hxyv40ra However, when attempting to incorporate this code within a Vue directive, the button event triggers and the console indicates that the class is removed, yet there is no visual chang ...

Trouble with ScrollView not scrolling on Nativescript-Vue

I am facing an issue with a scrollable view in my project. I have a list of items that should be scrollable, but for some reason it is not scrolling as expected. The structure involves a vertical stack layout wrapped in a scrollview, and inside the stackla ...

I need assistance in obtaining the hashed password

I am attempting to retrieve the hashed password for the admin user. Despite my efforts to hash the password, I am encountering difficulties when trying to insert it into the user object. import encryptor from '../helpers/password'; let hashed_ ...

Guide on transferring three js variable to an HTML label element

For my project, I am looking to pass three js values to the label of a div. The desired output is: stWay: stProposer: stTime: hello John 2017-09-07 I have successfully programmed a button to make div1 a ...

"Dispatching with Redux resets all other states back to their default values

Overview I am managing two states: isLogged and counter. The isLogged state is a boolean that the user can toggle between true and false to access specific pages. On the other hand, the counter state is a simple integer value that can be incremented or de ...

Importing a JavaScript file into another JavaScript file as text in React Native can be a convenient way

In my project, I have a file named MyFirstPage.js that contains the following code snippet: renderCards() { let icon = this.state.icon; .... .... .... } This code is responsible for rendering cards within the main render function. However, as the ...

Leverage Next.js routing in plain JavaScript without relying on React hooks

I am working on a NextJS app and I need to implement a function that can redirect to any page using Next.js routing. For example, after a user completes the signup process, I want them to be redirected to a specific page. So, I tried creating a reusable ...

Triggering keydown event on an Angular directive using jQuery's .trigger() function

After developing an edit directive that wraps an HTML input in a stylish frame, I moved on to creating a unit test. The goal was to verify that when I type into the input field, the form controller's dirty state is properly set. To simulate this acti ...

Organize intricate JavaScript Arrays

Similar Question: How to sort an array of javascript objects? I'm in the process of transitioning some of my older ActionScript 2.0 code to JavaScript. While most things are running smoothly, I've hit a roadblock when trying to numerically s ...

How can I retrieve the value of a radio button using jQuery

My goal is to retrieve the selected/checked radio button value using the .get function. I believe my code is correct, but the sequence seems to be off. $.get('burgerorder_check.php', function(data) { inputVal = $('input[type ...

The output of new Date() varies between app.js and ejs

app.get("/test",function(req,res){ var d = new Date(); res.send(d); }); When I access mydomain/test, it displays the output "2019-03-19T04:50:47.710Z" which is in UTC. app.get("/testejs",function(req,res){ res.render("testejs");}); Below is the content ...

Tips for combining values from two inputs to an angular ng-model in AngularJS

I am working with an angular application and I am trying to figure out how to combine values from multiple inputs into one ng-model. Here is an example of my current input: <input type="text" class="form-control input-md" name="type" ng-model="flat.f ...

Trouble getting CSS to load in Webpack

I'm having some trouble setting up Webpack for the first time and I think I might be overlooking something. My goal is to use Webpack's ExtractTextPlugin to generate a CSS file in the "dist" folder, but it seems that Webpack isn't recognizi ...

The installation process with Npm seems to be dragging and I'm seeing a significant number of "cache misses" for almost every library

Everything seems to be functioning smoothly on my local computer. However, when I run nodejs inside a docker container (docker run node:18) and clone a project, the process of typing npm install to download all libraries becomes extremely slow. It takes ar ...