AngularJS: The templateUrl is being rendered before the controller is able to execute any further actions

My current code is causing some trouble:

angular.module("cattle_feed_frontend", ['ngResource','ngRoute'])
    .config(['$routeProvider', function($routeProvider){
        $routeProvider.
            when('/',
                { 
                    controller: 'FeedController',
                    templateUrl: 'templates/FeedList.html'
                }).
            otherwise({
                redirectTo: '/'
            });

    }]) 
    .controller('FeedController', function($scope, feeds_factory) {

        $scope.feeds = feeds_factory.allFeeds();
    })
.factory('feeds_factory',['$http', function($http){
return {
    allFeeds : function(){
        $http.get("http://localhost:3000/feeds").then(function(response) 
         {
           return response.data;
         });
    }
}
}])

The issue arises in the controller where feeds_factory.allFeeds() is making an HTTP call to a 3rd party. The problem is that my template is being rendered before the HTTP call is made. This results in the ng-repeat in my template not displaying anything because $scope.feeds is set after the rendering process:

<tr ng-repeat="feed in feeds">
    <td>
        {{feed.ingredient}}
    </td>
    <td>
        {{feed.cost_kg}}
    </td>

</tr>

Answer №1

When using $routeProvider, it is important to let it know that your controller will make an HTTP request and needs to wait for the response. This can be achieved by using the resolve property of a route:

$routeProvider.
    when('/',
        { 
            controller: 'FeedController',
            templateUrl: 'templates/FeedList.html',
            resolve: {
                feeds: function(feeds_factory) {
                    return feeds_factory.allFeeds();
                }
            }
        }).
    otherwise({
        redirectTo: '/'
    });

Make sure to return the promise from feeds_factory:

factory('feeds_factory',['$http', function($http){
    return {
        allFeeds : function(){
            return $http.get("http://localhost:3000/feeds").then(function(response) {
                return response.data;
            });
        }
    }
}])

Finally, inject the feeds into the controller:

controller('FeedController', function($scope, feeds) {
    $scope.feeds = feeds;
})

Answer №2

To resolve the issue, consider updating your code as follows:

.controller('FeedController', function($scope,new_feeds_factory) {

    new_feeds_factory.getAllFeeds()
        .then(function(updates) {
            $scope.updates = updates;
        });
})

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

Vuejs unstyled content flash

I encountered an issue while loading a page with Vue. Initially, I am able to access variables like @{{ value }} but once the page is fully loaded, the variable becomes invisible. How can I resolve this issue? I have already included Bootstrap and all scri ...

What could be causing this Javascript Array() to generate an array containing just a single element?

In my next js app, I have the following function: export async function getServerSideProps(ctx) { const campaign = campaignInstance(ctx.params.address); const requestCount = await campaign.methods.getRequestsCount().call(); console.log(req ...

Vue's emission system, accessed through this.$emits, unexpectedly ceases functioning mid-function call

Within my Vue frontend, I have a function designed to emit updates to the parent component before and after sending a request to the server. The function in question is as follows: saveUpdates: async function () { const component = { doc: ...

Having trouble connecting the POST response object to my view

I've been trying to work out this problem for hours, scouring various sites and resources in search of a solution, but nothing seems to be working so far. The Problem Currently, I am developing a travelogue web application that enables users to log ...

Obtain non-numeric parameters from the URL in Angular 2 by subscribing to

How do I handle subscribing to a non-numeric parameter from a URL? Can the local variable inside my lambda function params => {} only be a number? Here's my code: getRecordDetail() { this.sub = this.activatedRoute.params.subscribe( ...

Hybrid application: Manipulate HTTP user agent header using AngularJS

I am currently developing a hybrid app using Cordova and Ionic. My current challenge involves making an HTTP request to access a server where I need to modify the user agent of the device in order to pass a secret key. $http({ method: 'GET&a ...

Zoom in and Zoom out functions in ngPdf with centered view

I have incorporated the pdf canvas to showcase PDFs on my AngularJS/Bootstrap application, and I must say, the preview feature is working exceptionally well. However, one thing that I would like to achieve is centering either my modal or the canvas itself ...

When using Rails to render a JSON page remotely, the JavaScript AJAX handler fails to capture the response

My goal is to have a form that can post remotely and then receive JSON data back for my JavaScript to process. Below is the code I am using: <%= form_tag '/admin/order_lookup', remote: true, authenticity_token: true, id: "order-lookup-submit" ...

Modify content or display picture within accordion panel based on its identifier

In my view, I have a model representing a list of items. Each item has a unique ID, which is included in the H2 header tag. The details of each item are displayed in a div below the header. Initially, there is an image within the header that is set to disp ...

Generating HTML elements on the server-side vs. retrieving data as JSON and dynamically creating elements using JavaScript

Looking to implement an AJAX search feature that will retrieve and display topics from a forum, including just the topic link and subject. My question is: Which method would be more efficient and quicker? Retrieve the threads list as a JSON string, co ...

When you click on a sublevel in the vertical CSS and JavaScript onclick menu, it disappears automatically

I'm a beginner when it comes to Javascript, and I'm still getting the hang of CSS/HTML. Currently, I am working on creating a vertical menu using CSS and javascript. My goal is to have the sublevels appear on the right side of the menu when someo ...

Even with the inclusion of the necessary JavaScript file before calling the DataTable function, $(...).DataTable continues to be

I have been struggling to implement a table on my website that dynamically populates data from my database. Despite researching various solutions online, I have yet to resolve the issue. Below is the code I am using. Please review it and point out any mis ...

Show only relevant dropdown options when a radio button is selected, and also automatically adjust options when the page

I am working on a form that includes radio buttons and a dropdown list. If the user chooses 'girls', I need to display only caroms and chess, which are specified in the girlsGames variable. If the user selects boys, I want to show the dropdown ...

Passing functions from a separate file as parameters in a Node.js route

Struggling to introduce modularity into my codebase as it has become messy. Every time I try to refactor, I encounter errors and end up with a dysfunctional program. The goal is to split my code into separate files, each handling their own tasks. If one f ...

Using AngularFire: How can you connect and bind data to the $scope efficiently?

Currently delving into the world of Firebase and noticing the differences between it and MongoDB. ...

Creating a column filter with ng-repeat in AngularJS for each (key, value) pair in a column

With a plethora of APIs to work with, I am currently using the (key,value) format in my ng-repeat to display data in a table. However, I now want to add a dynamic column filter for each column, but keep running into an error: filter: noArray. You can view ...

Issues with navigating routes in AngularJS

I'm currently learning Angular and having trouble with my routing setup in my application. I have a complex structure of nested modules, which makes me believe the issue lies within the injections. If anyone could provide some guidance, it would great ...

Node Js server unable to function properly in offline mode due to Service Worker malfunction

I'm currently working on creating a progressive web app (PWA) that prioritizes offline functionality. The source files are hosted on a NodeJS server. During testing, I noticed that when operating on a localhost node server, I only see the Chrome Off ...

Utilizing Vue to send information to the POST function

I am encountering an issue with passing data to the Vue.js post method. I am using vue-resource and according to the documentation, it should be structured like this: this.$http.post('/someUrl', [body], [options]).then(successCallback, errorCall ...

Connecting one page to another on the same page using Next.js

Hey everyone, I could really use some help with linking pages on Next.js. I understand how to create links, but here's what I'm trying to achieve: On my homepage, I have navigation links for courses, team, and contact in the navbar. When I click ...