Displaying JSON with AngularJS HTTP Get request won't work in my project

As I delve into the world of AngularJS, I find myself caught up in a puzzle that has consumed my entire evening. My goal is to fetch JSON data from a random generator and display it in the view using a service. While {{ main.title }} seems to be working just fine, the issue arises with ng-repeat="user in main.users" as {{ user.name }} fails to show anything. Where did I make a misstep?

Index.html

<html>
<head lang="en">
    <meta charset="UTF-8>
    <title>AngularJS Tutorial</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.4/angular.min.js"></script>
    <script src="app.js"></script>
    <script src="main.ctrl.js"></script>
    <script src="users.serv.js"></script>
</head>
<body ng-app="app" ng-controller="MainController as main">
<div class = "container">
    <h1>{{ main.title }}</h1>
    <div ng-repeat="user in main.users">
        <h2>{{ user.name }}</h2>
    </div>
</div>
</body>
</html>

app.js

angular.module('app', []);

main.ctrl.js

angular.module('app').controller('MainController', ['users', function(users) {
    var vm = this;
    users.get(function(data) {
        vm.users = data;
    });
    vm.title = 'Hello World';
}]);

users.serv.js

angular.module('app').factory('users', ['$http', function($http) {
    return {
        get: function (callback) {
            $http.get('http://www.json-generator.com/api/json/get/bJHFVOzrzC?indent=2').success(function(data) {
                return data;
            })
        }
    }
}]);

Answer №1

Make sure to call the callback function after the completion of the ajax request

angular.module('app').factory('users', ['$http', function ($http) {
    return {
        get: function (callback) {
            $http.get('http://www.json-generator.com/api/json/get/bJHFVOzrzC?indent=2').success(function (data) {
                callback(data);
            })
        }
    }
}]);

Demo: Fiddle

Answer №2

Arun provided a helpful answer, but another method I prefer involves returning the HTTP method from the factory. This way, you can handle success, error, or promises in the controller like this:

MainController.js

 angular.module('app').controller('MainController', ['users', function(users) {
        var vm = this;

        users.get().success(function (data) {       
            vm.users = data;   
        });

        vm.title = 'Hello World';
}]);

userService.js

angular.module('app').factory('users', ['$http', function($http) {
     return {
         get: function (callback) {
             return $http.get('http://www.json-generator.com/api/json/get/bJHFVOzrzC?indent=2');          
         }
     }
}]);

Answer №3

To regain control over the data received in an ajax response, you have two options. One is to pass a custom callback function to be executed after the data has been obtained, or you can directly manipulate the data within the success callback when making an $http.get(...) call for ajax requests.

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

Utilizing PHP to fetch data from a separate webpage

This is a question that has sparked my curiosity. I am not facing any particular issue that requires an immediate solution nor do I possess the knowledge on how to achieve it. I have been contemplating whether it is feasible to utilize PHP for fetching co ...

What steps can I take to expand this on a grander level?

I have a code snippet for a personality quiz, but I'm facing an issue with increasing its size. Here's the HTML code: <h3>1. What is your favorite color?</h3> <input type="radio" name="q1" value="A" /> A. Red. <input type="r ...

Express, the mongoose package delivers a response of an empty array

I have encountered a common issue regarding pluralization with mongoose default model names. Despite trying various solutions, the problem persists as I am getting an empty array as the result. In my local mongoDB database, there are 2 documents in the "us ...

I would greatly appreciate any recommendations on how to troubleshoot and

I've been working on the "Map the Debris" challenge at freecodecamp, and I'm facing an issue. While my code works fine in my PC's editor, it doesn't satisfy the conditions when I paste it into the website area. Any suggestions on how t ...

Transform array sequences into their own unique sequences

Reorder Array of List to Fit My Custom Order Current Output: [ { "key": "DG Power Output", "value": "6.00", "unit": "kWh", }, { "key": "DG Run Time", "value": "5999999952", "unit": "minutes", }, { "key": "Fuel Level (Before)", "value": "8.00" ...

Tips for accessing the current state/value in a third-party event handler?

Consider the following scenario: function MapControl() { const [countries, setCountries] = useContext(CountriesContext) useEffect( () => { ThirdPartyApi.OnSelectCountry((country) => { setCountries([...countries, country]) }) }) ...

Remove the most recently played sound from an array of sound using Vue.js

I've been trying to figure out how to randomize the sounds that play when a button is clicked, but I also want to avoid repeating the last played sound. It just doesn't sound right if the same sound plays repeatedly in quick succession. I'm ...

Discovering the object and its parent within a series of nested arrays

Is there a way to locate an object and its parent object within a nested array of unknown size using either lodash or native JavaScript? The structure of the array could resemble something like this: name: 'Submodule122'</p> I have been ...

Ways to activate the JavaScript/AJAX script upon the dropdown value modification

I am currently working on a Django project where I want to execute a JavaScript/AJAX script when the value of a dropdown changes. Interestingly, the same code functions properly for a button but not for the dropdown. Below is the HTML code containing the ...

Oops! It seems like there was an issue trying to access properties that are undefined while reading 'pipe' in Angular12

I encountered an issue when trying to send an AJAX request, displaying the following error message: ERROR TypeError: Cannot read properties of undefined (reading 'pipe') This error occurred in the ajax-loader.interceptor.ts class export class A ...

The attribute 'tableName' is not found within the 'Model' type

Currently in the process of converting a JavaScript code to TypeScript. Previously, I had a class that was functioning correctly in JS class Model { constructor(input, alias) { this.tableName = input; this.alias = alias; } } Howev ...

Trigger the Modal once the navigation step is completed

When navigating to a new page, I need to wait for the navigation process to complete in order for the modal template to be properly displayed on the destination page. public onOpenModal(item) { this.router.navigate([item.link]).then(() => { this. ...

The page reloads automatically following the completion of an ajax request

Hey there, I have a basic form with just a text field. When we submit the form, the data entered in the text field gets stored in the database through ajax. Although the ajax function is working properly and the data is being submitted, the page automatica ...

Scrolling using JavaScript's 'smooth scrolling' feature is currently disabled

Background of the Issue: I am in the process of creating a one-page website using Twitter Bootstrap 3 within an ASP.NET MVC project. The Challenge: My current challenge involves implementing 'smooth scrolling' functionality that scrolls to the ...

Error message: The call stack size has surpassed the limit, resulting in a RangeError. This issue is

I currently have a dynamic unordered list within my HTML file. Upon loading the page, certain list items are automatically added. The original format of the list is displayed as follows: <ul class="ui-front"> <li><div>1</div& ...

AngularJS app is not initialized by ngApp, only by ng-app

Up until now, I had believed that there was no difference at all between using the different formats of Angular directive names - ngApp, ng-app, x-ng-app should all work interchangeably. However, on this particular webpage, Angular doesn't seem to in ...

Ways to determine the height of a row within a flexbox

Is it possible to obtain the height of each row within a flexbox container using JavaScript? For instance, if there are 3 rows in the container, can I retrieve the height of the second row specifically? ...

Troubleshooting the issue: React Native Redux not navigating correctly using API IDs

Lately, I've been utilizing Redux for my application and it's been going well. However, I recently encountered a roadblock that has halted my coding progress temporarily. My current challenge involves creating a navigation system using the ID of ...

Angular.js not capturing x-access-token

When utilizing the POSTMAN Chrome extension to make an API call api.get('/me', function(req, res) { res.json(req.decoded); }); return api; By using x-access-token as a header with a valid token value, I receive a successful response. Howe ...

The battle between Google Visualization API JSON and ArrayToDataTable in Python, a nightmare of data types

Initially, I developed a basic static google visualization page using python The python source code is as follows: def print_graph_script(temp_table): # google chart snippet chart_code=""" <script type="text/javascript" src="https://www.g ...