Why does clicking to add to an existing array only result in the array being cleared instead?

Need help with an AngularJS question relating to scope binding and click events. I want to add one value on the first click and another value on the second click, but it's only returning an empty array and filling the first value again. Why is that happening?

scope.dbclickalert = function (scope, $watch) {
    var getCheckInDate = this.cellData.date;
    var formatcheckindate = new Date(getCheckInDate);
    var checkingdates = [];
    var curr_datecell = formatcheckindate.getDate();
    var padded_day = (curr_datecell < 10) ? '0' + curr_datecell : curr_datecell;
    var curr_monthcell = formatcheckindate.getMonth() + 1;
    var padded_month = (curr_monthcell < 10) ? '0' + curr_monthcell : curr_monthcell;
    var curr_yearcell = formatcheckindate.getFullYear();
    var date_stringcell =  + padded_month + "/" + padded_day + "/" + curr_yearcell;
    var checkindatestrg = "checkindate";
    console.log(checkingdates.length);
    if (checkingdates.length < 2) {
        alert("element exists in array");
        checkingdates.push('checkoutdate');
        checkingdates.push(date_stringcell);
        console.log(checkingdates + checkingdates.length);
    } else {
        checkingdates.push('checkindate');
        checkingdates.push(date_stringcell);
    }
    var setCheckInDate = el.hasClass('checkInDate');
    if (checkingdates === true) {
        alert('You have already set your check In Date');
    } else {
        el.addClass('checkInDate');
        $('#checkoutbar').addClass('datePickerchecout');
    }
    $(".date-cell").each(function removeclasses() {
        $(this).removeClass('true');
    });
    return getCheckInDate;
};

When I declare this outside of the function, I get an undefined error:

scope.checkingdates = [];
      scope.dbclickalert = function(scope, $watch){
         var getCheckInDate = this.cellData.date;
         var formatcheckindate = new Date(getCheckInDate);
         var checkingdates = scope.checkingdates;
         var curr_datecell = formatcheckindate.getDate();
         var padded_day = (curr_datecell < 10) ? '0'+curr_datecell : curr_datecell;
         var curr_monthcell = formatcheckindate.getMonth() + 1;
         var padded_month = (curr_monthcell < 10) ? '0'+curr_monthcell : curr_monthcell;
         var curr_yearcell = formatcheckindate.getFullYear();
         var date_stringcell = + padded_month + "/" + padded_day + "/" + curr_yearcell;
         var checkindatestrg = "checkindate";
         console.log(checkingdates.length);
           if (checkingdates.length < 2){
              alert("element exists in array");
              checkingdates.push('checkoutdate');
              checkingdates.push(date_stringcell);
              console.log(checkingdates+checkingdates.length);
          }else{
              checkingdates.push('checkindate');
              checkingdates.push(date_stringcell);
          }
         var setCheckInDate = el.hasClass('checkInDate');
          if (checkingdates === true){
              alert('You have already set your check In Date');
          } else{
              el.addClass('checkInDate');
              $('#checkoutbar').addClass('datePickerchecout');
          }
             $(".date-cell").each(function removeclasses() {
                $(this).removeClass('true');
             });
              return getCheckInDate;
      };

In the third version, the same data ("the date") is returned again if the same div has been clicked, but not if a second div with the same ng-click="dbclickalert()" is clicked. Why?

link: function(scope, el, attributes, dateSheetCtrl, $watch) {
          scope.checkingdatesarry = [];
  scope.dbclickalert = function(){
                 var getCheckInDate = this.cellData.date;
                 var formatcheckindate = new Date(getCheckInDate);
                 var checkingdates = scope.checkingdates;
                 var curr_datecell = formatcheckindate.getDate();
                 var padded_day = (curr_datecell < 10) ? '0'+curr_datecell : curr_datecell;
                 var curr_monthcell = formatcheckindate.getMonth() + 1;
                 var padded_month = (curr_monthcell < 10) ? '0'+curr_monthcell : curr_monthcell;
                 var curr_yearcell = formatcheckindate.getFullYear();
                 var date_stringcell = + padded_month + "/" + padded_day + "/" + curr_yearcell;
                 var checkindatestrg = "checkindate";
                 var checkoutdatestrg = "checkoutdate";


                if( $.inArray('checkindate', scope.checkingdates) !== -1 )  {
                     scope.checkingdatesarry.push(checkoutdatestrg);
                      scope.checkingdatesarry.push(date_stringcell);
                      console.log(scope.checkingdatesarry + scope.checkingdatesarry.length);


                }
                else{
                scope.checkingdatesarry.push(checkindatestrg);
                      scope.checkingdatesarry.push(date_stringcell);
                      console.log(scope.checkingdatesarry + scope.checkingdatesarry.length);


                  }


                 var setCheckInDate = el.hasClass('checkInDate');
                  if (scope.checkingdates === true){
                      alert('You have already set your check In Date');
                  } else{
                      el.addClass('checkInDate');
                      $('#checkoutbar').addClass('datePickerchecout');
                  }
                     $(".date-cell").each(function removeclasses() {
                        $(this).removeClass('true');
                     });
                     return  scope.checkingdatesarry;
  };

For those interested, the solution was to move the array out of the directive and into a service since the divs were being created with an AngularJS directive, resulting in multiple arrays instead of one global array.

Answer №1

The reason for the array being emptied every time the dbclickalert action is triggered is because you are redefining it as an empty list within the function.

var checkingdates = [];

To avoid this issue, you should declare the array outside the function like this:

$scope.checkingdates = [];  //If you changed $scope while injecting, use scope.checkingdates = [];

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

Best resolutions and formats for Nativescript-Vue application icons

I'm a newbie when it comes to Nativescript, and I'm looking to change the icon for my app. After doing some research, I found this command: tns resources generate splashes <path to image> [--background <color>] This command seems li ...

What could be the reason for the Express function Router() returning a value of undefined?

Currently, I am working with TypeScript and Express to develop an API that adheres to the principles of Clean Architecture. To organize my application, I have structured each route in separate folders and then imported them all into an index.ts file where ...

Storing binary data uploaded via AJAX in PHP on the server is essential for maintaining

I successfully imported a .png image file as an Array Buffer. var readSingleFile = function(e) { var file = e.target.files[0]; if (!file) { return; } var reader = new FileReader(); ...

Perform a series of clicks

I'm attempting to click a button multiple times. After each click, the button takes 1 second to load, then reappears and can be clicked again. My goal is to click this button a total of 5 times. for(i=0;i<5;i++) $('.class').click(); ...

What is the method to select a hyperlink that includes a variable in the "href" attribute and click on it?

Currently, I am in the process of creating acceptance tests utilizing Selenium and WebdriverIO. However, I have encountered a problem where I am unable to successfully click on a specific link. client.click('a[href=#admin/'+ transactionId + &apo ...

Utilizing Nicknames in a JavaScript Function

I'm dealing with a function that is responsible for constructing URLs using relative paths like ../../assets/images/content/recipe/. My goal is to replace the ../../assets/images section with a Vite alias, but I'm facing some challenges. Let me ...

Is it possible to set up AngularJS ui-router in JS files other than just the app.js (default) file?

Currently, I am utilizing angularJS, requireJS, and bootstrap to organize my project. However, as the title suggests, having all routers configured in app.js can result in a large and challenging file to maintain in the long run. Are there any solutions ...

Improving List performance with React.cloneElement

I am uncertain about the usage of React.cloneElement within a List component. Is it recommended to avoid using it, especially when dealing with a large number of elements in the list? Does React.cloneElement cause unnecessary re-renders that can be optimal ...

What is the best way to strip the text from a link that encompasses both text and an image using jquery?

I have a website with a list of items. Each item in the list has a link that includes both text and an image. Here is an example of the HTML structure: <li class="li-one" style=""> <a href="#" onclick="return ...

Establishing the Backbone router configuration

Having trouble identifying the issue with my Backbone router. Is there an error within this code block? The index route is functioning correctly, but the classes route doesn't seem to be triggered (for example, when I try navigating to a URL like loca ...

Error: props.addPost does not exist as a function

Help Needed with React Error: props.addPost is not a function. I am trying to add a new post in my app. Please assist me. import React from "react"; import classes from "./MyPosts.module.css"; import { Post } from "./Post/Post.jsx& ...

Saving a JSON object to a .json file using JavaScript

let project = { Name : "xyz", Roll no 456 }; What is the best way to save the data stored in the project object to a .json file using JavaScript? ...

The server is unable to process the request for /path

After browsing various posts, I am still unable to identify the root cause of my issue. I am developing a donation page for an organization and need to verify if PayPal integration is functioning correctly. The error I am encountering lies between my form ...

Include a requirement within an application/ld+json formatted script

I have a task to create an application using a script in the js+json format. It is crucial to include the person schema, which signals to Google and other search engines how to effectively interpret the structure of the page and its content. My current cod ...

Switch out bootstrap icons for angular material icons

I'm currently in the process of transitioning from using Bootstrap to Angular Material in an existing application. I need assistance with replacing the Bootstrap icons with Angular Material icons. Any help is greatly appreciated. <md-button class= ...

Tips on showcasing Javascript filter outcomes after at least 2 characters have been entered

Currently, I have implemented a filter search box that displays results as soon as a single letter is inputted. However, due to the large amount of data that needs to be filtered through, I would like the search to only show results when a minimum of two l ...

Automatically resizing images in a canvas when their resolution exceeds the canvas size in HTML5

I am currently using Html5, fabric.js, and JavaScript to upload multiple images to a canvas. However, there are instances where the uploaded image size exceeds that of the canvas. I am looking for a way to ensure that the image is set to a fixed size. v ...

Encountering an Error when Integrating Pusher (real-time data library) with Next.js: PusherRequestError - Unexpected status code 400

I encountered an issue while trying to integrate Pusher into my Next.js application due to Vercel's restriction on websockets in their serverless functions. The error message I keep receiving after running the program with Pusher is: error - unhandled ...

What is the correct way to customize colors for specific components in Material-ui?

Struggling with theming in Material-UI, particularly when it comes to customizing element colors. Some elements default to 'theme.palette.main.dark' and I want to override this behavior. For example, the TextField and SpeedDial components automa ...

performing functions concurrently within angularjs

I am currently utilizing angularjs 1.0 within my application. There is a dropdown on my cshtml page <select tabindex="2" id="Employee" ng-model="models.SelectedEmployee" ng-change="changeEmployee()" disabled="disabled" class="Answer" size="6"> < ...