Stop $watchCollection from initializing on start

I have an array called "$scope.postits" that I want to persist every time it changes. To achieve this, I added a $scope.$watchCollection on this element to monitor changes and save the data. The issue is that the $watch function gets triggered 3 times when the page loads (due to my test array having 3 entries). How can I prevent this? What could be wrong with my code?

View:

<div ng-controller="postitController as postit" class="container animate-bottom">
    <h2>Post-it !</h2>
    <div class="btn-container">
        <button ng-click="addPostit()" id="add-new-note" class="btn btn-primary">Add postit</button>
    </div>
    <div class="post-it-container">
        <div ng-repeat="postit in postits" class="postit">
            <a ng-click="removePostit(postit)" class="delete-postit glyphicon glyphicon-remove"></a>
            <textarea ng-model="postit.content" ></textarea>
        </div>
        <div ng-if="postits.length==0" class="no-postit well lead">Keep calm and enjoy a beer! There are no post-its here.</div>
    </div>  
</div>

JS Controller :

app.controller('postitController', function($scope, $http, $timeout) {
    $scope.postitsLoaded = false;
    var storage = {
        endpoint: "localhost/backend/ws.php",
        get: function() {
            $http({
                method: 'GET',
                url: this.endpoint
            }).then(function successCallback(response) {
                $scope.postits = response.data;
                $scope.postitsLoaded = true;
                console.log("initialization done") ;
            }, function errorCallback(response) {
                console.log(response);
            });
        },
        save: function () {
            $http({
                method: 'POST',
                url: this.endpoint,
                data: "postits="+ angular.toJson($scope.postits),
                headers: {'Content-Type': 'application/x-www-form-urlencoded'}
            }).then(function successCallback(response) {
                console.log(response);
            }, function errorCallback(response) {
                console.log(response);
                alert("error");
            });
        }
    }
    $scope.$watchCollection("postits", function (newValue, oldValue) {
        if(newValue === oldValue || !$scope.postitsLoaded){
            console.log("returning") ;
            return;
        }   
        console.log("watch triggered") ;
        storage.save();
    });
    $scope.addPostit = function() {
        $scope.postits.push({id:100, content:"foobar"});
        storage.save();
    };
    $scope.removePostit = function(postit) {
        $scope.postits.splice($scope.postits.indexOf(postit), 1); 
        storage.save();
    };
    storage.get();
});

Answer №1

After much trial and error, success has been achieved by utilizing $watch and setting the third parameter to true:

    $scope.$watch("postits", function (newValue, oldValue) {
    //this prevent $watch to be triggered on init 
    if(newValue === oldValue || oldValue === undefined  ){
        console.log("return") ;
        return;
    }   
    console.log("watch triggered") ;
    console.log(oldValue);
    console.log(newValue);
    storage.save();
},true);

This solution eliminates the need for using any flag.

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

Creating specialized validation for numeric fields in Angular2

Attempting to implement custom validation in Angular 2 has been a challenge for me. I have followed the necessary steps based on my understanding, but still struggling to get it working. import { FORM_DIRECTIVES, AbstractControl, ControlGroup ,FormBuilder ...

Guide to parsing and storing a JSON file in Node.js using AngularJS's $http.post functionality

EXCUSE THE POOR ENGLISH I am encountering an issue with capturing a JSON sent using $http.post from an angularjs to a nodejs with express (I have to send it because I cannot save a file on the server's client-side) The following is my code in angula ...

Having difficulties with implementing the throw await syntax in an async express handler in Node.js

const express = require("express"); const expressAsyncHandler = require("express-async-handler"); const app = express(); const func = async () => { return false; }; app.get( "/", expressAsyncHandler(async () => ...

Chat box custom scrollbar always positioned at the bottom

I have a personalized chat box where I included overflow-y for scrolling functionality. However, every time I input a message in the text box, it displays at the top of the scrollbar window. Is there a way to automatically show the most recent message I ...

Utilizing Angular to successfully obtain objects from a RESTful URL with numerous parameters

Is there a way for me to effectively create a factory that can retrieve data from /rest/company/:companyid/employee/:id? After attempting to use this URL in the factory, I encountered an error: Unknown provider companyidProvider Sincerely, Kyle Service ...

What could be causing the carousel to be hidden in a Next.js project?

My project involves utilizing the react-multi-carousel component to display a maximum of two stock photos. I made modifications to the next.config.js file as well. import Image from "next/image"; import Carousel from "react-multi-carousel&qu ...

Changing MySQL Limit arguments into numerical values

I'm encountering an issue with my Rest call to a MySQL database. I'm using a JavaScript object and sending it through a REST GET call with a Java back-end. requestParams: { pageStart: 0, results: 10 } I have configured ...

Develop an XML document with the use of either Javascript or PHP

I have an XML file that contains information about bracelets with photo details. <bracelets> <photo filename="b1.jpg" thumbnail="a1.jpg" description="aa" /> <photo filename="b2.jpg" thumbnail="a2.jpg" description="aa" /> & ...

The dot notation in JSON syntax allows for easy access

Recently, I've been struggling with referencing a variable in JSON dot notation within my meteor application. It seems that when trying to access respJson.userlower.name, userlower is not being recognized as a valid variable. Is there a workaround for ...

Positioning JQuery sliders

I've been working on a jQuery slider for my header, but I'm encountering an issue where the previous image drops down to the next container instead of staying in place and transitioning smoothly. It seems like there might be an error in my HTML/C ...

Switching between light and dark themes in a Next.js application with Ant Design v5 theme toggle

In my Next.js application using Ant Design v5, I am working on implementing a dynamic theme toggle to switch between light and dark modes. The issue I'm facing is that the initial theme settings work correctly, but subsequent changes to the isDarkMode ...

Is your Phonegap and Jquery app experiencing delays in script loading?

I recently developed a phonegap + JQM application and encountered an issue with the loading time of external JavaScript files. To elaborate, when the app starts, the initial file that appears is loader.html. In this file, I have included several JS files ...

When implementing JWT for route authentication, the webpage remains frozen in one spot

Currently, I am in the process of making modifications to a project. The front-end is built using Vue 2.0 and the back-end utilizes Node.js Express. To ensure security, I have implemented the JWT approach by requiring authentication for all pages except th ...

How to replace text using jQuery without removing HTML tags

One of the functions in my code allows me to replace text based on an ID. Fortunately, this function is already set up and working smoothly. $('#qs_policy .questionTitle').text("This text has been updated"); However, there is another ...

Undefined elements in an array of objects in Javascript

I've been working on creating an array of objects in JavaScript, but I'm facing an issue when attempting to print the array to the console in Chrome. It keeps returning undefined unless I print the array right after pushing new elements into it. ...

Tips for concealing an alert using an 'if' statement

There is an alert that pops up on a website only on specific days of the year. My query is: How can I make the alert hidden if the date is not one of those special days? I attempted the code below, but it seems to just delay the alert based on certain con ...

What is the best method for showcasing two images side by side in a column layout?

I need to showcase 2 images in a row using AngularJS, with the next two images in the following row and so forth. Img1 Img2 Img3 Img4 This is my code: <section id="content"> <div class="content-wrap"> <div class="container clearfix "& ...

The sidebar.querySelector method is not working as expected

Attempting to assign an 'active' class to the clicked 'nav-link' element in order for it to stay active on the next page the user navigates to. Encountering an issue with sidebar.getElementsByClassName is not a function showing up in t ...

What is the purpose of the "Dot" symbol in the "runtimeArgs" property of the launch.json file in Visual Studio Code?

As I opened my Visual Studio Code today, a notification greeted me about a new update. Without hesitation, I went ahead and installed it, assuming it would be like any other update I've had in the past. However, after updating to version 1.22.1, I enc ...

Employing promises for fetching data via XHR results in a promise that is still pending

Currently, I am experimenting with promises to handle asynchronous requests using XHR. Interestingly, I noticed that when I try to log the result within the .then function, it works perfectly fine. However, if I attempt to log it outside of this scope, it ...