Unable to utilize JavaScript objects extracted from JSON

Working on developing a web application using AngularJS has led me to encounter an issue. I have a PHP server that retrieves data from an SQL database and encodes it into JSON. Utilizing the Angular $http service on the client side, I am able to successfully fetch and parse the data. However, I am facing difficulty in utilizing the variable assigned with the fetched data.

factory.employees = factory.getEmployeesFromServer();

factory.getEmployeesFromServer = function() {
        return $http.get("http://localhost/scrumboard/get_user.php")
            .success(function(response) {
                for(var property in response) {
                    console.log("PROP: "+property);
                    if (response.hasOwnProperty(property)) {
                        console.log("Has ownProperty: " + property)
                    }
                }
                console.log(JSON.stringify(response));
                return response.data;   
            })
            .error(function(response, status, headers, config) {

            })
    }

The print of the properties only shows zeros and ones, but when the Stringify-print prints to the console, it displays the data correctly as an array with two objects:

[{"email_id":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="94e6fbf6cbf1fad4f3f9f5fdf8baf7fbf9">[email protected]</a>","user_name":"rob","first_name":"Robert","last_name":"Allen","password":"roballen","admin_right_id":"2"},{"email_id":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2e5c414c714b404f6e49434f4742004d4143">[email protected]</a>","user_name":"robad","first_name":"Roben","last_name":"Lena","password":"aleno","admin_right_id":"1"}]

Although I can use ng-repeat to loop through the data with the code snippet below, it does not display any text:

<li ng-repeat="emp in availableEmployees">
    <label  class="btn btn-primary" ng-model="checkModel" btn-checkbox>
        HELLO {{emp.user_name}}
    </label>
</li>

Debugging further, I inspected the employees object as shown in the image below:

Seeking assistance as a relative newcomer to web development and willing to provide more details upon request!

Answer №1

Your server call operates asynchronously. Within your factory code, you are linking the employees variable to the result of $http.get, which yields a promise.

Consequently, in your HTML, you are iterating over the properties of a promise object, leading to the bizarre output you are witnessing. Nevertheless, the console log accurately displays the data, although it is not associated with the property being iterated over.

To rectify this issue, adjust your factory code so that the outcome of the promise is assigned to the employees variable rather than the promise itself:

factory.getEmployeesFromServer().then(function(data){
    factory.employees = data;
});

factory.getEmployeesFromServer = function() {
        return $http.get("http://localhost/scrumboard/get_user.php")
            .success(function(response) {
                 for(var property in response) {
                    console.log("PROP: "+property);
                    if (response.hasOwnProperty(property)) {
                       console.log("Has ownProperty: " + property)
                    }
                }
                    console.log(JSON.stringify(response));
                    return response.data;

            })
        .error(function(response, status, headers, config) {

        })
}

Answer №2

It seems like you might be using the wrong variable in your ng-repeat statement within your view.
Try replacing availableEmployees with just employees and check if that resolves the issue, as it seems to be what you are assigning to your scope.

<li ng-repeat="emp in employees">
<label  class="btn btn-primary" ng-model="checkModel" btn-checkbox>
    GREETINGS {{emp.user_name}}
</label>
</li>

Answer №3

Your code has a problem because factory.getEmployeesFromServer does not immediately return the list of employees since it is asynchronous. One solution is to modify the factory function to only return the promise like so:

factory.getEmployeesFromServer = function() {
        return $http.get("http://localhost/scrumboard/get_user.php");
};

To access the list of employees, you will need to provide a callback function to the success method. This callback function should assign the necessary values to a model (for example emp) within your controller's $scope ($scope.emp), like this:

promise = factory.getEmployeesFromServer();
promise.success(function(response) {
    $scope.emp = response.data;
});

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

Ways to attach dynamic methods within a v-for loop

I am currently working on a situation where I need to dynamically assign methods to elements that are being generated by a template using a v-for loop. These methods will be assigned based on the value of a particular variable, specifically the 'btn.m ...

Ignoring templateUrl in AngularJS and Karma-Jasmine to prevent the occurrence of "Unexpected request: GET .../.html" error

Currently, I am developing an AngularJS application using ES6 in order to minimize the amount of work needed for transitioning to AngularJS 2.0. However, I have encountered some complexity when it comes to performing unit tests. My main focus now is to t ...

Learn the steps to successfully select a drop-down option by clicking on a button

Below is the HTML code for my select options: <select id="font"> <option value="School">School</option> <option value="'Ubuntu Mono'">SansitaOne</option> <option value="Tangerine">Tange ...

Is file timestamp utilized by Apache to verify if a resource has been changed?

Currently, I am working on an HTML page that references a large JavaScript file (1MB+) that is rarely updated. According to this source, the JavaScript file will not be resent if it hasn't been modified. I'm curious about how Apache determines i ...

Angular: attaching an identification number to an API endpoint

I encountered a problem that has left me puzzled: I am attempting to remove a row from a table by passing the ID of that row (known as the record) through the path of my API. However, for some reason it is not being recognized. Strangely enough, when I sub ...

Executing a javascript function from PHP when a form is submitted: a comprehensive guide

I am looking to trigger a javascript function from PHP when the form is submitted. This function will have access to PHP variables and will use AJAX to send them to a PHP script on another website. The code below serves as an example: <?php .... ..... ...

Angular JS: Distribute objects from a single array to various arrays or services

I have recently embarked on developing a basic app using Angular JS, utilizing a service/factory to manage data and enable the addition of objects. Within the array of various individuals (listed in the html), you can include them as candidates by employi ...

Issues with CSS and Node Express

I'm currently experimenting with some code and running into a problem. Using Express, I noticed that only the CSS selector for the body element is working. However, if I remove the body tag, then the next container works, but the ones after that do n ...

Determine the Total of a Column in jqgrid

Hey there, I'm looking for a way to calculate the total sum of the "montant" column in my jqgrid and then display it below the grid as "Total: *total amount*". Here is the code for my grid: <sjg:grid id="gridtable" caption="Quittance Payé ...

Using jquery and Ajax to extract data from nested JSON structures

Need help with modifying a code snippet for parsing nested JSON format [ { "name":"Barot Bellingham", "shortname":"Barot_Bellingham", "reknown":"Royal Academy of Painting and Sculpture", "bio":"Barot has just finished his final year at T ...

Adding tween.js seems to have caused the button click event to stop triggering

After adding the code line to tween my display box, the click event is no longer triggered. There are no errors in the console. How can I resolve this issue and what might have caused it? createjs.Tween.get(directionsbox, { loop: false }).to({ x:800, y: ...

Scrollable container with jQuery draggable functionality

I am currently working on implementing a draggable list that I want to contain within a scrollable div. $( ".draggable" ).draggable(); Here is the fiddle I have created for this: http://jsfiddle.net/YvJhE/660/ However, the issue I am facing is that the ...

Utilizing GraphicsMagick with Node.js to Extract Page Frames from Multi-Page TIF Files

I am currently working with a JavaScript script that can successfully convert a single page TIF file to JPEG. However, I am facing difficulties in determining whether "GraphicsMagick For Node" (https://github.com/aheckmann/gm) has the capability to extra ...

What is the method to retrieve the color of a linearGradient in an SVG at a particular

I am working on a unique progress bar that uses a linear gradient and a small ellipse to indicate the completion percentage. The AngularJS binding updates the completion percentage and a function is called. My challenge is to change the color of the ellip ...

Having trouble converting a JSON array into a JavaScript array upon creation

I have encountered this question multiple times before and despite trying various solutions, I have not been able to find success. Summary: My goal is to retrieve the array from the classes.json file and then assign the data in the variable classes from d ...

Conceal the Navigation Bar Upon the Pop Up's Appearance

I Designed a Landing Page with a Fixed Mobile Nav Bar at the Bottom. There is also a Pop-Up Form that appears when clicked. How can I make sure the Nav Bar is closed when the form pops up? This issue is blocking the Send Button. Is it possible to achiev ...

Clicking buttons in AngularJS

I've developed a button that, when clicked, triggers an AJAX call and binds the server response obtained through AJAX to a table using AngularJS. The issue I'm facing is that the data should appear on the webpage on the first click of the button, ...

Tips for managing the State with AppContext()---Need help figuring out how to handle

Why does setting the state userHasAuthenticated to true in the login function result in isAuthenticated being logged as false (staying the same in App.js as well)? Also, when trying to use it in the Home Component, it still shows false. //-------------- ...

Extract JSON array without any accompanying objects

I am attempting to parse this JSON data, { "listname": "red", "lists": [ { "id": "01", "name": "paw", "list": [ { "id": "A", "name": "pawa", "bar": "foo" }, { "id": ...

Elements that are added dynamically will not inherit the correct CSS styles, requiring JavaScript to style them properly

My <ul> element dynamically adds <li> elements, and I am attempting to make the first <li> wider at 63% while the others are at 60%. However, the first one is only getting a width of 60%. Any thoughts on why this might be happening? I ne ...