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

Display a hidden div on hover using JQUERY

How can I make a hover popup appear when submitting a form, and have it disappear only when the mouse is out of both the popup div and the submit button? Currently, the hover popup shows up but disappears when entering the popup. Can someone assist me in r ...

Issues arise in TypeScript when attempting to assign custom properties to a Vue component

I was working on implementing Vue middleware and faced an issue while trying to add a custom property to one of my components in Vue. Here's the code snippet: middleware.js: import { VueConstructor } from 'vue/types'; function eventPlugin(v ...

disable angular ui router functionality for specific links

Currently, I am looking to implement the bootstrap accordion in my Angular application. The angular ui-router is being used for navigating through different pages. However, I have come across an issue where the accordion requires an <a href="#Collaps ...

Creating multiple routes within a single component in Angular without triggering unnecessary redraws

Within the ChildComponent, there is a reactive form that allows for data entry. Upon saving the filled form, the route should be updated by appending an id to the current route. Currently, when saving, the component renders twice and causes screen flicke ...

A guide on how to efficiently update and submit a reactive form with a single click of the submit button in Angular

Currently, I have a view component setup where clicking the edit button directs me to the register component for form updates using patchvalue. The issue that I am facing is that when I update and register the form using the same button, it creates anothe ...

Utilizing JavaScript For Loops for Code Repetition

Apologies for the ambiguous question title - struggling to articulate this properly. Essentially, I have some JavaScript code that I am looking to streamline by using a for loop. $('.q1').keyup(function () { if ($.inArray($(this).val().toLo ...

"What is the best way to use jQuery to create a toggle effect where one button controls the state

I'm looking to improve the efficiency of my code, but I'm not sure where to start in terms of making it more concise and organized. Any suggestions on how to streamline this code and keep it neat would be greatly appreciated. $(document).ready(fu ...

What is the best way to generate a group and organize a list that works seamlessly with AngularJS and Bootstrap?

Hey there, I have a dataset that looks something like this (just a basic example). fruit, apple, $1 fruit, orange, $1 fruit, banana, $1 vegetable, sprouts, $2 vegetable, carrots, $1 Drink, water, $1 Drink, milk, $2 I am looking to create a list that gro ...

Updating Vue component with mismatched props

I am looking to optimize the Vue component where data is received in varying structures. Take for example Appointment.vue component: <template> <div> <div v-if="config.data.user.user_id"> {{ config.data.user.user_id ...

What is the best way to identify the differences between two non-unique arrays in JavaScript? I initially relied on underscore, but I am willing to

Given two arrays: firstArray = [{id: 'id1'}, {id:'id2'}, {id:'id3'}, {id:'id3'}] secondArray = [{id: 'id1'}, {id:'id2'}, {id:'id3'}] The expected output is [{id:'id3'}] This ...

Encountering issues with installing @vue/cli on Linux Ubuntu

Currently facing an issue while attempting to install the Vue CLI on Ubuntu (WSL). After running both yarn add global @vue/cli and npm install @vue/cli --global, it seems like the commands were successful. However, upon checking the version using vue --v ...

Navigating through items and organizing based on several criteria

In JavaScript, I am currently learning about accessing objects and sorting them based on multiple conditions. As a beginner in JavaScript, this may seem like a very basic question to some. My task involves sorting based on the 'status' field. va ...

Tips for creating a flexible Cell component in react-big-calendar:

Is there a way to make the cell of react-big-calendar flexible depending on the number of events, and enable scrolling? Here is a screenshot showcasing my issue: https://i.stack.imgur.com/K2h69.jpg ...

Using onclick events, manipulating innerHTML, and dynamically generating tables

Below is the code snippet: window.onload=function(e){ //Created by Firestar001 var X; var Y; var board=""; var rizzalt=document.getElementById("rezzalt"); var letters = new Array; letters = ["A","B","C","D","E","F","G","H","I","J"]; for(a=0; a<=9 ...

Scroll down only if the user is not actively scrolling

Struggling with JavaScript once again and feeling frustrated! Can someone please assist me? I am currently working on a basic chat application that retrieves content from a text file using an AJAX request. The content refreshes every few seconds, scrollin ...

JSON Generator's date formatting convention

One method I use to create a JSON object is through JSON-GENERATOR I prefer the date to be formatted like this: 2017-12-31 [ '{{repeat(5, 7)}}', { equityPriceList: [ { date:'{{date(new Date(1970, 0, 1), new Date(),[DD ...

In TypeScript, how are angle brackets like methodName<string>() utilized?

Could someone please assist me in understanding why we use angular brackets <> in typescript? For example, I have provided some code below and would appreciate an explanation. export class HomePage { constructor(public navCtrl: NavController) ...

"Discrepancy in results between JSON stringify and JavaScript object conversion

I need to save this object in a database, but first I have to send it to the backend. Recorder {config: Object, recording: false, callbacks: Object, context: AudioContext, node: ScriptProcessorNode…} However, after using JSON.stringify(recorder) The r ...

How can I incorporate dynamic fields into a Typescript type/interface?

In my Typescript interface, I have a predefined set of fields like this: export interface Data { date_created: string; stamp: string; } let myData: Data; But now I need to incorporate "dynamic" fields that can be determined only at runtime. This me ...

Creating a custom directive in AngularJS to validate input values

I created a custom HTML form with the following structure: <div class="row col-lg-offset-3"> <div class="form-group col-lg-6" ng-class="{ 'has-error': userForm.Age.$invalid && userForm.Age.$dirty}" show-errors > & ...