Troubleshooting issues with AngularJS $watch not triggering properly

Even though Deep watch has been activated in the factory, it is not triggering. What steps can be taken to resolve this issue and ensure that an event is triggered when the 'name' value changes?

Javascript Code:

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

app.controller('FirstCtrl', function($scope,testFactory) {
  $scope.obj = testFactory.obj;

});

app.controller('SecondCtrl',function($scope,testFactory){
  $scope.obj = testFactory.obj;
  $scope.valueChange = testFactory.valueChange;
});

app.factory('testFactory', ['$rootScope',function ($rootScope) {

    var factory = {};

    factory.obj = { 'name':'John Doe'};

    $rootScope.$watch(factory.obj,function(){
        alert('Value Changed');
    },true);

    factory.valueChange = function(){
      if(factory.obj.name == 'John Doe'){
      factory.obj.name = "Jane Doe";
      }
      else
      {
        factory.obj.name = "John Doe";
      }
    };

    return factory;

}]);

Html Code:

  <body >
    <div ng-controller="FirstCtrl">
    <h4>Value bound with FirstCtrl and factory</h4>
    <input type="text" ng-model="obj.name"/>
    </div>

    <div ng-controller="SecondCtrl">
    <br>
    <br>
    <h4>Value from SecondCtrl. This shows that the bind between factory and controller is working</h4>
    <p>{{obj.name}}</p>
    <h4>Value updated directly in the factory</h4>
    <button ng-click="valueChange()">Change Value</button>
    </div>
  </body>

Plunker: http://plnkr.co/edit/LhHOa2NehWGVEfpHfKJQ?p=preview

Answer №1

Give this method a try:

$rootScope.$watch(function () {
    return factory.obj;
}, function(){
    alert('Value Updated');
}, true);

Plunker Link

A more effective approach would be to monitor changes in the controller instead of the factory:

app.controller('SecondCtrl',function($scope,testFactory){
    $scope.obj = testFactory.obj;
    $scope.valueChange = testFactory.valueChange;
    $scope.$watch('obj', function () {
        alert('Value modified');
    }, true);
});

In this scenario, both $scope.obj and testFactory.obj reference the same object in memory. Therefore, it doesn't matter which one you choose to observe.

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

Incorporating a Menu within a TableCell using Material-UI

I have a desire to incorporate Google's Material UI Menu Item inside a TableCell, following their documentation guidelines here in this illustration: https://i.stack.imgur.com/IffEM.png This is my current method: import React from 'react' ...

The functionality of Material UI tooltip is not functioning properly when accessed on mobile devices

Attempting to transform Tooltip into a controlled component that relies on the onClick event. While this setup works well on mobile and web, it loses its original functionality of showing the Tooltip on hover. Is there a way to make the Tooltip function ...

The function to navigate, 'navTo', is not defined and so it cannot be read

I am trying to create a navigation button in my SAPUI5 application deployed on Fiori _onPageNavButtonPress: function () { var oHistory = History.getInstance(); var sPreviousHash = oHistory.getPreviousHash(); if (sPreviousHash !== ...

How can users change the displayed Twitch channel?

My coding skills aren't the greatest, especially when it comes to something like this. I've tried searching for a solution with no luck, so I apologize if this is too basic or impossible. I have a simple page that loads up Twitch with a predefin ...

The 'file' property of undefined throws an error in ng-file-upload

I am currently exploring the functionality of ng-file-upload from this repository: https://github.com/danialfarid/ng-file-upload I have successfully implemented the basic setup as follows: HTML: <section ng-controller="MyController"> ...

What are some ways to display multiple divs within a single popup window?

I am attempting to create the following layout: Here is what I have been able to achieve: In the second picture, the divs are shown separately. My goal is to display the incoming data in a single popup like in the first picture, but I am having trouble a ...

What steps can I take to modify my webpage, like a dashboard, on the internet?

Whenever I click on a menu item in the sidebar of my HTML file, I want only the body section to change without affecting the navigation or sidebar content. For instance, if I select the "Coding Convention" menu in the sidebar, I would like the page to swi ...

When using VueJS routing with the same component, the OWL Carousel does not get triggered

Hello I am currently experiencing an issue with VueJS rendering images into a Carousel plugin (OwlCarousel) when loading the same component with different variables. When initially loading the page with images, everything functions correctly and the caro ...

Multiple requests were made by Ajax

I am facing an issue with my ajax code where it is being called multiple times. Below is my php code: (While loop extracts results from a database. For brevity, I have included just the modal and dropdown menu sections.) $rezPet = mysqli_query($kon, "SEL ...

Customize Material-UI icons dynamically by changing their props in an array

I am looking to change props (color, size) for multiple icons in an array using Material-UI v4: const ICONS_ARRAY: React.ReactNode[] = [ <AlertCircleCheckOutline />, <AppleSafari />, <MotionPlay />, <AppleKeyboardCommand />, <Fil ...

Ways to expand the border horizontally using CSS animation from the middle

Currently, I am experimenting with CSS animation and I have a query regarding creating a vertical line that automatically grows in length when the page is loaded. I am interested in making the vertical line expand from the center in both upward and downwar ...

Ways to unzip binary information in node.js

Once I have decoded my data from base 64 to binary, my next step is to unzip this information. In my project, I am using node.js instead of PHP, which has a convenient gzdecode() function for decompressing data. However, with node.js, I am unsure of how t ...

Cleve js does not include delimiters in its date output

In my Vue.js project, I decided to implement a date input field using cleave.js. After passing the following options: options="{date: true, delimiter: '/', datePattern: ['m', 'd', 'Y']}" I encountered an issue wh ...

What are the methods for providing both successful and unsuccessful promises, with or without data?

Seeking guidance on how to return a promise and an object named output before or after the $http call in AngularJS, specifically using Typescript. How can I ensure it works correctly? topicNewSubmit = (): ng.IPromise<any> => { var self = t ...

Images not showing in Vue.js

I have been working on setting up a carousel using bootstrap-vue. It is being generated dynamically through an array containing three objects with keys such as id, caption, text, and image path. The issue I am facing now is that while the caption and text ...

Using jQuery in Angular, you can add a div element to hidden elements by appending

So, I have a hidden div that I want to show on button click. And not only do I want to show it, but I also want to append another div to it. The show and hide functionality is working fine, but the appending part seems tricky when dealing with hidden eleme ...

Using a data() object in Vue to fill out form fields efficiently

My data retrieval process from mongodb involves obtaining the data and transferring it to the client side using the following approach: error_reporting(E_ALL); ini_set('display_errors', '1'); require '../vendor/autoload.php'; ...

What are the steps to switch the dropdown values?

I am facing an issue with swapping values in two dropdowns. The scenario is that I have a dropdown with minimal values and another one with maximum values. If a value selected in the first dropdown is greater than the value in the second dropdown, they nee ...

Leveraging JS Variables within Twig Template

I am trying to incorporate a JavaScript variable into Twig. Despite attempting to implement the solution mentioned here, my code below does not render the map properly. If I remove the part between "var polylineCoordinates" and "polyline.setMap(map);", th ...

Validate Bootstrap - Transmit data from all form fields to external PHP script

Is there a way to send all input field values to a remote PHP file using Bootstrap Validator? In my log in form, I have two input fields. I'm utilizing Bootstrap Validator's remote validation on both of them. However, each validation only sends ...