Experiencing duplicate execution of $onChanges in AngularJS version 1.6

I might be overthinking this, but that's why I'm seeking help. :)

Note: In the example below, the controller alias for the component is "ctrl". var ctrl = this;

Imagine we have a component with two bindings, one of which is optional:

bindings: { 
   params: '<', 
   company: '<?' 
}

Sometimes the company binding is present, and sometimes it's not.

The $onChanges function looks like this:

ctrl.$onChanges = function(changes) {
    if (changes.params || changes.company) {
        console.log('executed');
    }
}

It appears that when both bindings are updated, $onChanges is triggered twice. The first time, the value of ctrl.company (the binding) in the component is null, even though I updated it with a value. The second time, ctrl.company does have its value.

It's possible that the OR operation in the conditional is not correct. I'm just not entirely sure how $onChanges works.

I'll provide more clarity if my explanation of the issue is confusing.

Thank you in advance.

Answer №1

Referencing AngularJS code:

$onChanges(changesObj) - This function is called whenever one-way (<) or interpolation (@) bindings are updated. The changesObj is a hash containing keys representing the names of the properties that have changed, along with values in the form of

{ currentValue, previousValue, isFirstChange() }
. This function is useful for triggering updates within a component, such as cloning the bound value to prevent unintended mutation of the value.

It seems that you have 2 bindings: params and company, which are causing the $onChanges function to be triggered twice.

If you only want the log to be written once, you can use the && operator like this:

if (changes.params && changes.company) {
    console.log('executed');
}

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

Eliminate an array from another array if a specific value is present in an object

I've been struggling with removing an entire array if it contains an object with a certain value within. I've searched high and low, but haven't been able to find a solution that fits my specific problem. In my data structure, I have arrays ...

Creating a fantastic Image Gallery in JavaScript

As I work on creating a basic gallery page with html and css, everything seemed to be running smoothly. However, upon testing it in Google Chrome and IE, the onmouseover function is not responding as expected. The idea is for a larger image to display in t ...

Preventing default action within a passive event listener is not possible because the target is considered passive. This issue is particularly relevant with Three.js Track

I'm currently developing a 3D application using Three.js. One of the key components in this project is implementing a control system for the camera, which I have achieved using TrackballControls. However, as I tried to add an event listener, I encount ...

"Adding an active class to a link based on the current page and locale: A step-by-step

Looking to add an active class to the subheader menu on the active page, but facing issues when changing the locale in the link. While it works for links like my-site/my-page, it doesn't work for links like my-site/fr/my-page. Utilizing Storyblok head ...

The Vue router is unable to access the store state

My Vue application is utilizing vue-router and vuex. I acquire an authentication token from my API, store it in localStorage, and then push it to the store. However, when the page refreshes, the app is unable to retrieve the token from localStorage and the ...

Using BeautifulSoup to extract data from a webpage containing JavaScript

Hello everyone! I am reaching out for help once more. While I am comfortable scraping simple websites with tags, I recently came across a more complex website that includes JavaScript. Specifically, I am looking to extract all the estimates located at the ...

No results appearing in the output section

While developing a website using React, I encountered an error that said useState is defined but never used in the navbar component. To address this, I made changes to my ESLint configuration in the package.json file: "rules": { "eqeqe ...

What is the significance of the reserved keyword $scope in an AngularJS controller

I'm just starting out with Angular and recently stumbled upon this fiddle that illustrates how nested controllers work. I tried renaming $scope to $abc, but it didn't seem to work. Does this mean that $scope is a reserved keyword in AngularJS? f ...

Selenium Scrolling: Improving Web Scraping Efficiency with Incomplete Data Extraction

I have been attempting to extract product data from a website that utilizes JavaScript to dynamically render HTML content. Despite using Selenium, implementing scrolling functionality to reach the end of the page, and allowing time for the page to reload, ...

The metallic material in Substance Painter appears as a dark shade in A-Frame

After exporting an object as gltf from Substance Painter, I am importing it into my A-frame scene. Strangely, the metallic outer material appears dark in my current scene while other materials like plastic appear white and are visible. Despite already ha ...

Creating a table in VueJs and populating it with values retrieved from an MSSQL database in a .NET Core web application

I am developing a table within a .NET Core Web Application that includes multiple rows and columns filled with data retrieved from a MSSQL server through a WEB API Given the need for numerous rows and columns, I am considering using a for loop inside my & ...

Having trouble accessing PDF files on Electron framework

Despite following the advice provided in similar questions' answers, such as including webPreferences: { plugins: true } in the options when creating a BrowserWindow instance, I am still encountering issues. Every attempt to open or view a PDF ...

Issue with loading dynamic content on a webpage using HTML and JavaScript through AJAX

I am currently using the jQuery UI Tabs plugin to dynamically load HTML pages through AJAX. Here is the structure of the HTML code: <div id="tabs"> <ul> <li><a href="pageWithGallery.html" title="pageWithGallery">Gallery< ...

Exploring the variance in outcomes when directly accessing an AuthService state versus utilizing a function in a React AuthContext

I am currently working on creating an AuthContext, but I am encountering an issue with changing the state of a variable. Here is the code snippet: index.js import Head from "next/head"; import Image from "next/image"; import styles fro ...

What methods can be used to determine if a webm file contains audio or video content?

In the process of creating an uploader using ReactJS, I encounter an issue related to identifying whether uploaded files are video or audio. Specifically, when users upload audio files with a .webm extension (e.g., music.webm) and the MIME type is set as & ...

Implementing a loading spinner while using AngularJS $http.get request with the help

I'm looking to display a spinner while making an $http.get request. Here's a snippet of my code : AngularJS section : var portalSDM = angular.module('portalSDM', ['ui.router', 'agGrid', 'angular.filter', ...

Detecting collisions using CSS animation

I'm currently working on a unique "game" project. Check out the code snippet here: jsfiddle function update() { coyote.applyForce(gravity); coyote.edges(); coyote.update(); cactus.update(); if (coyote.intersects(cactus)){ alert("colisio ...

Objects vanish 10 seconds after appearing [Angular2, *ngFor]

My Angular2 template is quite straightforward: <span *ngFor="let item of items"> {{ item.description }} </span> Here is the TypeScript logic for it: let list = new Map(); for(let j = 0; j < 100; j++) { list.set(j, { description: j.toS ...

Implementing the rendering of HTML stored in an array in Angular

I have an array that includes an object with HTML elements which I would like to render in Angular. Here is the array: { name: "rules", key: "rules", value_before: "<tr><td>revisit_in_some_days</td><td>less_then</td>td> ...

Creating a personalized notification box that is compatible with various screen sizes and web browsers on android devices with the help of

After successfully implementing a custom alert box to hide the header with JavaScript, I encountered an issue when trying to use it on different browsers and Android devices. The alert box appeared misplaced on the page and was too big for certain Android ...