The $OnChange function fails to activate when passing an object by reference

Hi there, I've encountered a problem in my code that I'd like some help with. In my example, I have two components: Parent Component and Child Component. Both components share a field called rules.

The Parent Component passes the rules field to the Child Component using bindings ('<' one-way binding).

The issue arises when I try to update the rules field within the Child Component using $timeout. The onChange event does not trigger as expected when the data is updated.

Everything else works fine except for this specific behavior when passing an object by reference during a timeout process, which simulates an ajax call. I'm wondering why this happens and how I can force the onChange event to fire whenever the object is changed.

Below is the example illustrating my use case:

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

app.component("parent",{
  template:`ParentCmp-{{$ctrl.rules}}
            child- <child rules="$ctrl.rules"></child>`,
  controller:['$timeout',function($timeout){
    this.$onInit= function(){
      this.rules = { name: "Rule1" , Description: "Description" } ;
      this.updatedRules = { name: "UpdateRule1" , Description: "Update Description" }
      var self = this;
     $timeout(function(){
            self.rules = self.updatedRules;
            console.log("update rules",self.rules);
    },3000);
    }
  }]
});

app.component("child",{
  template:"childCmp-{{$ctrl.rules}}",
  bindings:{
    rules: '<'
  },
  controller:['$timeout',function($timeout){
    this.$onInit= function(){
      //this.rules = {};
    }
    this.$onChange = function(changes){
      console.log("onchange event",changes);
    }
  }]
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
<div ng-app="app">
  
  <parent></parent>
  
</div>

Answer №1

There is a typo in the code snippet. It should be $onChanges instead of $onChange in the child component

this.$onChanges = function(changes){
      console.log("onchange event",changes);
    }

See it in action on this Plunker

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

Can you identify the mistake in the XML response?

I encountered an issue with my PHP code (getRout.php) which is meant to respond in XML format. The error message I received was: XML Parsing Error: no element found Location: http://127.0.0.1/direction2/getRout.php Line Number 1, Column 1: edit To view ...

Troubleshooting issues with Angular's scope functionality

Here is my controller: angular.module('app', []) .controller('ctrl', ['$scope', function ($scope) { $scope.daysPerMonth = new Date(year, month).getDate(); }] ); This is the corresponding html: <div ng-app> <h1&g ...

What is the method for retrieving a specific value following the submission of an AngularJS form?

Here is how my form begins: <!-- form --> <form ng-submit="form.submit()" class="form-horizontal" role="form" style="margin-top: 15px;"> <div class="form-group"> <label for="inputUrl" class="col-sm- ...

Create an input field dynamically by utilizing the append method in jQuery

Concern: As part of an edit page, I am working on appending an input field from a modal window to an existing panel while retaining the format of the rest of the fields. The user is currently able to create and add the new field using the code provided in ...

Tracking the progress of file uploads using Ajax

Currently, I am working on integrating file upload using Ajax and Php on my local Apache server. This is strong text. $('.uploadButton').click(function(){ var formData = new FormData($(this).closest('.fileUploadFor ...

JSDoc encounters issues when processing *.js files that are produced from *.ts files

I am currently working on creating documentation for a straightforward typescript class: export class Address { /** * @param street { string } - excluding building number * @param city { string } - abbreviations like "LA" are acceptable ...

Struggling to retrieve the JSON information, but encountering no success

Here is the javascript code snippet: $.getJSON("validate_login.php", {username:$("#username").val(), password:$("#password").val()}, function(data){ alert("result: " + data.result); }); And here is the corresponding php code: <?ph ...

ag-grid's onGridReady function is not functioning properly

I am trying to dynamically load ag-grid when a button is clicked, but I have encountered issues with both of my approaches. Here is my code for the first method: onBtnClick(){ this.gridOptions ={ onGridReady : function(){ console ...

Avoiding ChartJS tooltips from being cut off

I've been exploring how to prevent chartjs from cutting off its tooltips, but I haven't been able to find a config option to address this issue. https://i.sstatic.net/Knzvd.png Here's what I've attempted so far: <script> ...

Servlet does not parse $http GET parameters

I'm encountering an issue where my Angular $http call is sending the userId, but the servlet is not able to receive the request parameter. I am trying to fetch the parameter using request.getParameter("userId"); Below is the code snippet for referenc ...

Sending a user to an external website through an XML response

In my current project, I am utilizing jQuery to fetch a PHP file. The PHP file executes a cURL request to an external website in order to obtain information for a payment request. The external site responds with XML data structured as follows: <Request ...

Parsing JSON as a sequence of individual characters

Currently encountering an issue and seeking guidance from anyone who may have experienced this before and knows what's going on. Utilizing $resource to fetch data from our WebAPI. (angularJS controller code) Controller.service.common.GetData.get({ ...

Renew Firebase Token

Currently, my email and password authentication flow in web Firebase JavaScript involves generating a token that I then verify on my node.js backend using firebase-admin. To make things easier, I store this generated token in the browser's local/sessi ...

Utilizing iOS Local Storage for Efficient Form Submission Handling

I feel like my brain is on the verge of exploding. I just can't seem to get this to work as intended, and I'm struggling to pinpoint the issue. Currently, I have a form that needs to be processed using AJAX. Before proceeding with that, I want ...

NodeJS: Speed up your workflow by compressing video files

In my quest to enhance the performance of my application, I am seeking ways to compress images and videos to their smallest possible size without sacrificing quality. This process is known as lossless compression. While the imagemin package has proven eff ...

Determine the type of a nested class within TypeScript

Utilizing nested classes in TypeScript is achieved through the following code snippet: class Parent { private secret = 'this is secret' static Child = class { public readSecret(parent: Parent) { return parent.secret } } } ...

Top Method for Incorporating Syntax Highlighting into Code Blocks - React Sanity Blog

I'm currently exploring the most effective method to incorporate syntax highlighting into my react sanity.io blog. Here's a look at the article component I've developed using react: import React, {useEffect, useState} from "react"; import ...

Even after applying trim() function, PHP's return statement still adds spaces unnecessarily

My function is supposed to return a boolean, but for some reason, it is adding spaces at the beginning of the string. Even after using trim(), the spaces persist. What could be causing this unexpected behavior? PHP function checkFile($v){ $result = is_ ...

The image failed to load in React/Express

I'm currently working on a React/Express app and I've encountered an issue with images not loading. Instead, I see the message "could not load the image." The CSS styles are loading fine, but the images are not showing up. I suspect there might ...

Enhancing SVG graphics dynamically with JavaScript and ensuring compatibility across different web browsers

I am currently working on incorporating an element into an existing SVG file. Interestingly, the process runs smoothly on Chrome and Firefox but encounters issues on Edge. I aim for it to function seamlessly on the latest versions of all three browsers, wi ...