The functionality of $watch in AngularJS is not meeting the desired outcomes

Within my controller, I am looking to receive notifications when the value of a certain variable changes. Specifically, I want a function to be triggered whenever this variable is updated. To achieve this, I am utilizing the $watch method in AngularJS. Here is an example of how my code is structured:


var Canvas = angular.module('canvas');

Canvas.controller("excelOperation",function($scope,Data,SharedData,$http){

    $scope.tbody=$scope.$parent.shared.previews;

     $scope.$watch('$parent.shared.previews',function(newVal,oldVal){
        console.log("WORKING");
     })

     setInterval(function(){
         console.log($scope.$parent.shared.previews);
     },1000)

    /**
     * Populate table function to populate excel table
     */
    $scope.populateTable=function()
    {

    }
})

angular.bootstrap(document.getElementById("page"), ['canvas']);

However, I have encountered an issue where the $watch does not seem to be functioning properly unless I manually refresh the page. Despite the fact that the setInterval is correctly displaying the changed variable value, the $watch fails to trigger.

Side Note: $scope.$parent.shared.previews is an object

My question is: what mistake am I making? And is there a better approach to achieving what I intend to do?

Answer №1

Observing the transformation of an object's attribute demands a deep watch. Additionally, to monitor a variable in the parent scope, it might be more suitable to code it as follows $scope.$parent.$watch(...).

var keepWatch = true;
$scope.$watch('$parent.shared.previews', function(newVal, oldVal) {
    console.log("OPERATIONAL");
}, keepWatch);

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

Issue with $http.get in fetching information from PHP server

Dealing with duplicate keys error in AngularJS, PHP, and MySQL I have been working on a web-based system and encountered an issue with ng-repeat displaying duplicate keys. I am unsure how to resolve this issue. The select all brand functionality seems to ...

Tips for showing an Object with nested Objects in Vue.js

Looking for guidance on displaying a JSON object in Vue.js with the following structure: { "1": [ "15-16", "16-17", "17-18", "18-19" ], "2": [ & ...

What causes $(this) to stop functioning post successful execution?

Here are the code snippets I'm currently working with: $(this).removeClass('page larger').addClass('current'); $(this).siblings().removeClass('current').addClass('page larger'); Interestingly, when I try to pl ...

Node.js application encounters a challenge with Swagger UI requirement not being met

My Node.js application utilizes Electron v15.3.1 and includes a Swagger UI for OAS file viewing, specifically version 4.6.1. Due to a security vulnerability in the Swagger UI, I need to upgrade it. Initially, I attempted to resolve the issue by running np ...

"Unleashing the Power of AngularJS: Implementing a Global Error Handler to Display and

When building my website, I have multiple Angular apps that require a global error handler to track and display alerts for errors with codes like 500 and 401. Here is what I have so far: In order to create a global error handler module, I've set up t ...

Express 4 app.use not functioning properly

My backend setup is fairly straightforward with a few routes. I prefer to keep the route logic separate from the server.js file, but for some reason, when I make a POST request to the route, it returns a 404 error. In the server.js file: // Import necess ...

Navigate using history.push with user Logout Icon

Currently, I am utilizing a Material UI icon as a logout button in my project. Here is how I have implemented it: function logout(props:any){ localStorage.removeItem("token"); return( <Redirect to="/login" /> ) //props.history.push("/log ...

JavaScript prototypal inheritance concept

During my free time, I like to dabble in JavaScript, but I’m currently struggling with this particular topic. var person = new Person("Bob", "Smith", 52); var teacher = new Teacher("Adam", "Greff", 209); function Humans(firstName, lastName) { this. ...

Creating a prototype function in JavaScript

I am attempting to create a JavaScript prototype function that replicates the Python syntax of 'a' in 'abc'. The function works correctly in one example, but not in another. Can you help me identify what mistake I made? String.proto ...

Transform nested JSON objects into a JSON array using JavaScript

Hey there! I've got this JSON structure that I'm trying to convert into an array without having to iterate over each element. Is there a JavaScript function that can help me achieve this? { "ES": { "130": { "code": "A Coruсa", ...

Deactivate the button in the final <td> of a table generated using a loop

I have three different components [Button, AppTable, Contact]. The button component is called with a v-for loop to iterate through other items. I am trying to disable the button within the last item when there is only one generated. Below is the code for ...

What is the best way to incorporate setTimeout in a loop using Coffeescript?

window.onload = -> boxOrig1 = 10 boxOrig2 = 30 canvasW = 400 canvasH = 300 ctx = $("#canvas")[0].getContext('2d'); draw = (origin,dimension) -> ctx.clearRect(0, 0, canvasW, canvasH) ctx.fillStyle = 'rgb(200,0 ...

Implementing Choice of UI-Masking to Accommodate Either Five or Nine Digits for Zip Code Input

I need to use the UI_mask feature to allow a flexible format for zipcodes, either (xxxxx-xxxx or xxxxx). To accomplish this, I have already implemented < input type="text" name="zipcode" ui-mask="99999?-9999" ui-mask-placeholder ng-model="zipCode"> ...

JavaScript Regular Expression Assistance Domain Snatcher

I am in the process of developing a JavaScript Regex and I am struggling to find the right pattern to match a specific domain. Let me provide an example for better understanding. I need a regex that can identify any domain that exclusively contains (text. ...

The function onClick does not function properly when used with the <p> element, but it works flawlessly with the <button> element

export function SignoutButton() { return ( <p onClick={() => signOut({ callbackUrl: "/" })}> <IoIosLogOut /> Logout </p> ); } I was struggling with a function in my next.js project that wasn't wo ...

What steps can I take to guarantee that a select change event occurs following the setting of ngmodel in Angular2?

I am facing an issue with a select element wherein a basic (change) handler is attached along with an ngmodel. Whenever an <option> with a ng value is set, the change handler triggers before the [(ngModel)] reflects the new values. <div> ...

Unexpected package version changes occurring due to bower install

I am currently using bower 1.3.12 Here is the content of my bower.json file: { "name": "my_project", "version": "0.0.0", "authors": [ "ME <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="660b0326030b070f0a4805090b ...

What could be causing my Angular/Express GET request to function properly while the POST request does not

My button setup includes Updates.getUpdates, which is working fine. However, Updates.postAnUpdate returns a 404 error. $scope.postUpdate = function () { console.log($scope.update); Updates.postAnUpdate($scope.update); Updates.getUpdates().the ...

Effortlessly switch between CSS animation styles while adjusting animation settings

My HTML element with animation is defined as follows: <div id="box"></div> The box starts by moving 200 pixels to the right, taking 4 seconds to complete. .anim { animation-name: anim; animation-duration: 4s; animation-t ...

Eliminating clutter in bespoke event handlers - eliminating the necessity for the 'event' parameter

I have a project where I am creating objects that will trigger custom events, and I am using jQuery's bind and trigger functions to handle this task. Here is an example of how I am implementing it: function MyObject() { var _this = this; th ...