AngularJS: The watch for the array is being triggered during the initial load even though the array is not being modified

               <div class="category">
                  <div ng-dropdown-multiselect="" options="categories" selected-model="selectedCategories" extra-settings="categoriesSettings" translation-texts="customTexts"></div>
                </div>

  $scope.$watch('selectedCategories', function(newValue, oldValue){
    console.log(newValue);
    console.log(oldValue);
    $scope.loadPosts();
  }, true);

  $scope.$watch('selectedCities', function(newValue, oldValue) {
    console.log(newValue);
    console.log(oldValue);
    $scope.loadPosts();
  }, true);

Upon the initial page load, these two watch functions are activated. It seems unusual that they would trigger during loading when the array is not being modified.

Answer №1

Watcher behavior is accurately described here. By including

if (angular.equals(newValue, oldValue)) { return; }
within the callback, your problem can be resolved.

Answer №2

Quoted from the Angular Documentation (right before the first example)

Once a watcher is set up on the scope, the listener function will be executed asynchronously (using $evalAsync) to initialize the watcher. In certain cases, this may not be ideal because the listener gets triggered even when there's no actual change in the watch expression result. To address this situation within the listener function, you can compare the newVal and oldVal. If these values are exactly the same (===), then it indicates that the listener was called during initialization.

To avoid this issue, you can check if newValue !== oldValue or introduce a variable to bypass the initial check.

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

Tips for resolving the npm glob-parent dilemma

Vulnerability in glob-parent <5.1.2 Detected Severity Level: moderate Description: Regular expression denial of service - More information at https://npmjs.com/advisories/1751 Resolution: fix available through `npm audit fix` Affected Package: node_modu ...

Styling for jQuery (and javascript) code snippets

Is it just me, or does anyone else feel like they want to write javascript and jQuery in a different structure after making numerous mistakes with curly brackets and parentheses? I wish there was an IDE that could automatically collapse the code back into ...

modify the URL records within the GetJson function

My current address is "http://localhost:8000/index", and when I execute the following jQuery code: $.getJSON("1",function(data) { .....code }); It redirects to "http://localhost:8000/index/1". This works fine for now. ...

Steps to gather all the images within a directory

Take a look at this demo When you click on the "next" button, new images are loaded from the internet. In my application, all the images are stored in the img/image folder with names like 1.jpg, hi.png, etc. My question is, how can I display these image ...

Exploring data that is nested within its parent

I'm struggling to understand the concept of Nested selections or how to apply it to my specific situation. Here is an example of the JSON data format I am working with: { 'name': 'root' 'children': [ { &ap ...

Displaying a popup containing a div when clicking on a link

I need assistance with creating a link that will display a div in a popup window. Here is the link I am working with: <li><a class="newAttachmentType" onclick="getFiles(true)">Move to somewhere</a></li> Also, here is the div that ...

Retrieving a Table Row from a TableView in Titanium Mobile

Does anyone know where the actual tableViewRows are stored within a TableView? When inspecting the TableView, I can see the headings for the Rows but not the Rows themselves. Can someone point me in the right direction to find where these Rows are contai ...

Combine Firebase and Stamplay services to leverage the power of Firebase Authorization in conjunction with Stamplay's Stripe integration

After successfully developing an App with Firebase as the backend, my next step is to implement Stripe for charging users and sending payments (or PayPal if it's a suitable alternative). Delving into solutions online, I've discovered that most of ...

The select dropdown does not automatically refresh when the array value changes

I am facing an issue with a select dropdown that is populated by an array filled with data from the server response: myApp.controller('mController', function($scope, $routeParams, $http, contextRoot) { var dataObject = {} $scope.arr = [ ...

Display a preloader image while waiting for the content to load using jQuery or AJAX

Hey there, I could really use some help with a little issue. I've been trying to use the click() and load() functions to bring my content into a specific CSS class. $("#feed").click(function(){ $(".homefeed").load("feedcontainer.php"); ...

The requested resource does not have the 'Access-Control-Allow-Origin' header in nginx

Although I have come across many similar questions, none of them have helped me solve my specific problem. jQuery.post( 'http://example.com/api_offer/get_time_left', function(data) { console.log('get time'); }, 'json'); ...

"Using Vue's v-model directive in conjunction with a select input

I'm attempting to set any option within my select input as a value in an object. My goal is to utilize v-model for this, but I'm still unsure of the process. Below is my current attempt: <div class="select-wrapper"> <select r ...

Is it possible to utilize Nuxt context within nuxt.config.js?

I am utilizing nuxt-i18n and @nuxtjs/auth in my project. I am looking to configure the auth.redirect option to support i18n as shown below: // nuxt.config.js export default { modules: [ '@nuxtjs/auth', 'nuxt-i18n', // .. ...

What is the best way to extract an object from an array that only includes one element, and that element is an object?

Here is the output of my updated function: db.collection('SOCIAL').get().then((snapshot) =>{ snapshot.docs.forEach(doc => { tempData.push(doc.data()) }) return tempData }) I want to store these valu ...

What is the jQuery alternative for the classList property in vanilla JavaScript?

Currently, I am working on a collaborative project with two acquaintances. One of the requirements is to stick to either vanilla JavaScript selectors like document.getElementById("thisDiv"); or jQuery selectors such as $("#thisDiv"); to maintain consis ...

What is the best way to keep my data within a global variable?

$(function(){ let spaceTravelersData; $.getJSON('http://api.open-notify.org/astros.json', retrieveData); function retrieveData(data) { spaceTravelersData = data; } alert(spaceTravelersData.people[0].name) }); I a ...

Using AngularJS promises within a loop

I have been working on a code snippet that iterates through the list of reports, modifies each one's name, and performs an update operation. Everything seemed to be in order when there was only one report in the list. However, things went haywire when ...

React-Native-SVG encountered an error: Invariant Violation - the component "RNSVGGroup" could not be found in the UIManager

Trying to create an SVG in React-Native using react-native-svg. I have set up a React-Native-CLI. After doing some research, I attempted to solve the issue on my own and found something useful. I tried running cd ios && pod install. I wasn't ...

Error: Attempting to assign a value to a property of #<Object> that is read-only

I'm working on a task management application and encountering an issue when trying to assign an array of tasks stored in localStorage to an array named todayTasks. The error message being thrown is causing some disruption. https://i.sstatic.net/uFKWR. ...

Ways to store a JSON string in a variable

When utilizing the ajax function, I am able to retrieve my JSON string. Here is an example: $.ajax({ type: "POST", url: "http://localhost/./Service/GetPageInfo", dataType: "json", contentType: 'application/json' ...