having trouble accessing a JavaScript array in AngularJS

Hey there, I'm currently working on a web application using AngularJS and I'm facing an issue with querying arrays. Check out the code snippet below:

var angulararray = [];
bindleaselistings.bindleaselistingsmethod().then(function(response) {
  angular.forEach(response.data.data.LeaseList, function(value, key) {
    angulararray.push(value);
  });
}, function(error) {});
console.log(angulararray);
debugger;
var found = $filter('filter')(angulararray, {
  id: accountnumber
}, true);
if (found.length) {
  $scope.selected = JSON.stringify(found[0]);
} else {
  $scope.selected = 'Not found';
}

The console.log shows the expected array content. I've included a screenshot for reference https://i.sstatic.net/QDs8a.png

While debugging the line

var found = $filter('filter')(angulararray, { id: accountnumber }, true);
, I noticed that angulararray appears to be empty. Can anyone point out what might be wrong in my code? Any assistance would be greatly appreciated. Thank you!

Answer №1

Your code is experiencing issues with asynchronous execution. The API call and the code following it are running in parallel, resulting in the angulararray variable being empty outside of the API call. To fix this, consider moving your filtering logic inside the success callback of your API.

var angulararray = [];
bindleaselistings.bindleaselistingsmethod().then(function(response) {
    angular.forEach(response.data.data.LeaseList, function(value, key) {
        angulararray.push(value);
    });
var found = $filter('filter')(angulararray, {
    id: accountnumber
}, true);
}, function(error) {});
console.log(angulararray);

if (found.length) {
    $scope.selected = JSON.stringify(found[0]);
} else {
    $scope.selected = 'Not found';
}

Answer №2

Your issue appears to be related to asynchronous programming. It seems like your code is executing before the promise has been resolved.

The reason you are seeing the response in the console.log is because your debugging tools provide a real-time view of the variable. As soon as the variable is resolved, the console will display the result of the resolved promise.

var angularArray = [];
bindLeaseListings.bindLeaseListingsMethod().then(function (response) {
    angular.forEach(response.data.data.LeaseList, function (value, key) {
        angularArray.push(value);
    });
    console.log(angularArray);
    debugger;
    var found = $filter('filter')(angularArray, {
        id: accountNumber
    }, true);
    if (found.length) {
        $scope.selected = JSON.stringify(found[0]);
    } else {
        $scope.selected = 'Not found';
    }
}, function (error) { });

Answer №3

If you want to modify how you filter your variable, consider implementing the following approach:

 let foundItem;
 const length = angulararray.length;
 for(let i=0; i<length; i++){
  if(typeof angulararray[i]['AccountNumber'] === 'undefined') {
    $scope.selectedItem = 'Not found';
  }
  else {
     foundItem = angulararray[i];
     $scope.selectedItem = JSON.stringify(foundItem[0]);
  }
 }

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

Learn the process of eliminating a class utilizing this JavaScript function

This script is designed to identify and manipulate elements with the class menu-option-set. When an element within this class is clicked, it adds the class "selected" to that specific element while removing it from all others in the list. My goal is to en ...

AngularJS: Tips for bypassing filtering when inputting values outside of the range [1,2,3,4]

Is there a way to prevent filtering when entering certain numbers in the text box, like 0 or 5? <div ng-app=""> <input type="text" ng-model="search"> <div ng-repeat='val in [1,2, 3, 4] | filter:search'> {{val}} </div> ...

Tips for showing the value in the subsequent stage of a multi-step form

Assistance is required for the query below: Is there a way to display the input field value from one step to the next in multistep forms? Similar to how Microsoft login shows the email in the next step as depicted in the image below: ...

IE8 and IE9 encountering "Access is denied" error due to XML causing XDomainRequest (CORS) issue

Sorry if this seems repetitive, but I am unable to find a definitive answer to similar questions. Whenever I attempt to make a CORS request for XML, I consistently encounter an "Access is denied" JavaScript error in IE8. The code I am using is based on t ...

What is the best way to trigger an event from a child component to a parent component in

parent.component.ts public test(){ //some code..... } parent.component.html <app-child (eventfire)="test($event)"></app-child> In this scenario, the child component button is displayed within the parent component. However, there i ...

swap between style sheets glitching

My website features two stylesheets, one for day mode and one for night mode. There is an image on the site that triggers a function with an onclick event to switch between the two stylesheets. However, when new visitors click the button for the first ti ...

When attempting to print using React, inline styles may not be effective

<div styleName="item" key={index} style={{ backgroundColor: color[index] }}> The hex color code stored in color[index] displays correctly in web browsers, but fails to work in print preview mode. Substituting 'blue' for color[index] succe ...

How to reference an object from an external file in TypeScript using Ionic 2 and Angular 2

I am currently developing a mobile application with Ionic2 and have integrated a simple online payment service called Paystack for processing payments. The way it operates is by adding a js file to your webpage and then invoking a function. <script> ...

JavaScript is utilized to implement the k-means clustering algorithm, which demonstrates convergence yet lacks stability in its

Although I understand the concept of convergence, I am puzzled by the fact that the results vary each time the algorithm is refreshed, even when using the same dataset. Can someone point out where my methodology might be incorrect? I've been strugglin ...

Comparison of Uint8Array and Uint8ClampedArray

Can you explain the distinction between Uint8Array and Uint8ClampedArray within JavaScript? I've heard that Uint8ClampedArray is specifically utilized for pixel manipulations on canvas. Could you elaborate on why this array type is recommended for suc ...

AngularJS does not function upon reloading the browser

I am currently working on a new project that involves the following components: Node.js (v0.10.37) Express micro framework Jade templating engine Angular.js (latest) Material design library (material.angularjs.org) Jquery One issue that I am facing is r ...

I'm having trouble with my .Refine feature when attempting to create a conditional input field. Can anyone help troubleshoot this issue?

I devised a feature in my form that generates additional input fields if the user selects 'yes'. How can I make these input fields mandatory and display a warning message when 'yes' is selected? const FormSchema = z.object({ type: z.e ...

Can you help me understand how to access data from a selected option?

Is there a way to ensure that selecting black from the dropdown will trigger the reading of the src attribute? What modifications are needed in this code? $('.select').click(function() { var lalala = $(this).val(); $("#gallery .imgsx"). ...

Guide on adding a timestamp in an express js application

I attempted to add timestamps to all my requests by using morgan. Here is how I included it: if (process.env.NODE_ENV === 'development') { // Enable logger (morgan) app.use(morgan('common')); } After implementing this, the o ...

Is there a way to retrieve all "a" tags with an "href" attribute that contains the term "youtube"?

My goal is to capture all a tags that have the href attribute containing the word youtube. This task requires the use of jquery. ...

Is there a way for me to verify if a number is represented in exponential form?

Is there a way to determine if a number is in exponential form? I encountered a situation in my code where normal integers are being converted to exponential notation when adding or multiplying them. For instance, performing the operation 10000000*1000000 ...

The Facebook login popup has been disabled

My current challenge involves using a Facebook app to authenticate my users. If the user is not logged in to Facebook (which I verify with FB.getLoginStatus()), I provide them with a button to log in. The issue I am facing is that the pop-up for logging in ...

Unable to reinitialize MUI DatePicker after keydown event

Encountering an unusual behavior that defies explanation has left me puzzled. You can explore the code sandbox here. I am attempting to enable resetting a readOnly field by pressing DEL or BACKSPACE, but it seems to be ineffective. Oddly enough, I can suc ...

Transfer data via ajax to the controller

I need assistance with storing a file in my database using Tabulator without having a form already created. I am currently creating a simple input element like this: var editor = document.createElement("input");. After clicking the file, it trigg ...

Move on to the following iteration within a (Typescript) .forEach loop by using setTimeout

Within my array, I have a list of image URLs that I need to update the src attribute of an img tag every 10 seconds. To achieve this, I am using a forEach loop which includes a setTimeout function that calls a DOM manipulation function (replaceImage) as sh ...