angular js is unable to set the property of undefined

In my current project, I have a list of JSON objects called $scope.phones and a directory filled with JSON files containing extra data about each phone. My goal is to go through these files and extract additional information to enhance the details in my phone list:

phonecatControllers.controller('PhoneListCtrl', ['$scope', 'Phone',
function($scope, Phone) {
$scope.phones = Phone.query();

var myTimer = window.setTimeout(function() {

    for (var i = 0; i < $scope.phones.length; i++){ 
        var weight = 0;             
        Phone.get({phoneId: $scope.phones[i].id}, function(phone) {
            weight = phone.sizeAndWeight.weight;
            $scope.phones[i].weight = weight;           
        });     
    };
} , 1000 );

$scope.orderProp = 'age';
}]);

The setTimeout function is used to ensure that the code only runs after $scope.phones are populated. Although it might be considered a bit of a workaround, it's currently functioning fine. However, an issue arises with the line:

$scope.phones[i].weight = weight;   

This error "cannot set property of undefined" occurs because trying to access this outside the .get method works without errors, but the updated value of weight remains confined within the .get method.

Answer №1

Patiently await the arrival of the phone list before embarking on a looping journey:

Phone.query().then(function(phones){
  for(var i=0; i<phones.length; i++){
    var weight = 0;             
    Phone.get({phoneId: phones[i].id}, function( phoneDetails) {
        weight = phoneDetails.sizeAndWeight.weight;
        phones[i].weight = weight;           
    });
  }
}

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

What is the importance of including "declare var angular" while working with Typescript and AngularJS?

I've been working on an AngularJS 1.7 application that's coded entirely in TypeScript, and there's always been one thing bothering me. Within my app.module.ts file, I have this piece of code that doesn't sit right with me: declare va ...

Executing a series of post requests within a loop and handling nested promises

Hello, I'm looking for some assistance! I'm attempting to send a post request for each item in an array. The issue I'm facing is that I need to aggregate the responses from each post request and then pass the count array back to the callin ...

Unable to access a function defined in $scope within the $http service while in the same controller

I attempted to relocate a function from my JS file to my Angular controller. This move was motivated by the fact that I am calling this function from inside the controller and it would be more logical to have it contained there rather than in a separate fi ...

Implementing Dropzone in an Angular MVC5 project

For more information about dropzone, visit this link I am currently implementing dropzone as my file upload handler with the combination of angularjs and MVC5. The challenge I'm facing is getting the Http post request to go from the angularjs servic ...

Is there a method in the dir-pagination directive for angularjs that allows me to retrieve all the records from the current page in pagination?

Is there a method to retrieve all records on the current page of the dir-pagination directive by @michaelbromley? If you need assistance, you can refer to this link: dir-pagination, where I am looking to extract a collection of 5 records ranging from 100 ...

Expanding a feature that modifies the CSS properties of every input element

Creating a text tracking (letter-spacing) demonstration where range sliders are used to update CSS properties. I'm looking to improve the functionality so that the labels also update dynamically, without repeating output2.textContent = this.value;. An ...

Using jQuery to submit a form and update values

I am currently working with a datatable that includes a detail column with an edit button. Upon clicking the edit button, I pass the ID as a parameter and fetch all the values associated with that ID to display in a form. However, when I edit the values an ...

What steps should I take to improve the performance of this MySQL query in order to increase the number of concurrent calls

When we execute the query below to retrieve data from the DB1.Data table, it takes longer to complete. The output of this query represents concurrent calls derived from CDR information. Mysql query select sql_calc_found_rows H,M,S,(TCNT+ADCNT) as CNT fro ...

react-ga4 is sending multiple view events repeatedly

After setting up a Google Analytics account and creating a new property, I integrated the tracking ID with react-ga4 for my Album ItemPage as shown below: const ItemPage = () => { const {user} = useContext(AuthContext); let { item } = useParams ...

Utilizing multiple API requests within a single Angular service

I am using Angular $http requests to access an API and retrieve information about various football teams. If I were only dealing with one team, it would be simple - I would create a Service that makes the request and then use that function in my controlle ...

What could be causing the browser to only partially display an image?

Have you encountered any issues with the browser not displaying an image fully? It seems like there may be a problem with the image download or rendering process, causing only part of the image to load. My application utilizes node and socket.io. Below ar ...

I am experiencing issues with my slash command handler, as it seems to be malfunctioning without any accompanying error messages

After successfully adapting my command handler to work with slash commands, I encountered some new challenges: 1 - When attempting to use the /ping command, an "interaction failed" message appears without any errors in the console. 2 - Upon inspection, I ...

Problem with locating elements using Selenium xpath

While using selenium and xpath, I encountered a peculiar issue. On a page, there are 25 <a> tags with nested <img/> tags. I am trying to retrieve all these elements using the findElements() method. Interestingly, upon inspecting the page source ...

Tips for utilizing webpack with angularjs

I am a newcomer to the world of angularjs and webpack. I have been accustomed to working with angularjs using the following folder structure: app js app.js controller.js service.js directive.js routes.js abc.js xyz.js templates home.html faq.htm ...

Creating a fixed navigation bar for an ecommerce website

Recently, I purchased a webshop and I am trying to implement a sticky header that remains at the top of the page all the time. Unfortunately, none of the solutions I've tried seem to be working, and I'm stuck on how to proceed. Is there anyone ou ...

How to incorporate parent class attributes into a JSON response utilizing the Struts 2 JSON plugin

Presenting my current setup public abstract class BaseAcion extends ActionSupport { private String result; private String message; //getters, setters } public class MyAction extends BaseAction { private String myFirstField; private S ...

Experiencing the error message "delete(...).then(...).error is not a function" while attempting to remove a file from Firebase storage using AngularFire and TypeScript

I'm trying to implement the code snippet from Firebase documentation to delete a file and then upload a new image in the same directory on Firebase Storage. However, I keep encountering an error message saying "delete(...).then(...).error is not a fun ...

What is the best way to utilize Jackson mapper with java.io.Serializable type fields?

I encountered a scenario where POJOs are inheriting from an abstract superclass that has methods like getId() and setId() defined with the type java.io.Serializable. When deserializing a JSON string to my concrete POJO classes, I face the following excepti ...

Filtering HTML tables to display only one instance of each value

I have a 300x11(rowXcolumn) html table that I wanted to filter like Excel or Google Sheets's filter. Upon researching, I came across the code below on a website. While it works as desired, there is an issue where it displays the same value multiple ti ...

What is causing the constant failure of the httpr.send() method?

I had a similar code running before, but unfortunately, I seem to have lost it. Despite trying different approaches, the PHP code just won't execute. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8& ...