The output from the Angular .then function is not showing up on the webpage

Within my stucontrollers.j, I have the following code:

/// <reference path="../angular.js" />
var stucontrollers = angular.module("stucontrollers", []);
stucontrollers.controller("GetStudentsList",
    function GetStudentsList($scope, $http) {
    $http({
        method: 'GET',
        url: '/api/students'
    }).then(function(data) {
        $scope.students = data;
    });
});

Additionally, in my view, I've included this:

<div ng-app="StudentApp">
    <div ng-controller="GetStudentsList">
        <table>
            <thead>
                <tr>
                    <th>Id</th>
                    <th>FistName</th>
                    <th>LastName</th>
                    <th>Age</th>
                    <th>Gender  </th>
                </tr>
            </thead>
            <tbody>
                <tr ng-repeat="item in students">
                    <td>{{item.Id}}</td>
                    <td>{{item.FirstName}}</td>
                    <td>{{item.LastName}}</td>
                    <td>{{item.Age}}</td>
                    <td>{{item.Gender}}</td>
                </tr>
            </tbody>
        </table>
    </div>
</div>

In my app.js, you'll find the following code:

/// <reference path="../angular.js" />
var module = angular.module("StudentApp", ["stucontrollers"]);

Lastly, my StudentsController.cs has the following snippet:

// GET: api/Students
public IQueryable<Student> GetStudents()
{
    return db.Students;
}

I'm facing an issue where the list of students only appears in the response of the page inspector and not on the actual page. Any suggestions on what could be causing this? Thank you.

UPDATE I can now view my data in the console, however, it still doesn't display on the page. Below is the data displayed in the console:

data
:
Array(2)
0
:
{Id: 1, FirstName: "Juan", LastName: "Dela Cruz", Age: 25, Gender: "Male"}
1
:
{Id: 2, FirstName: "Maria ", LastName: "Makiling", Age: 30, Gender: "Female"}

Answer №1

Make sure to invoke $scope.$apply() after assigning the value.


$http({
  method: 'GET',
  url: '/api/students'
}).then(function(data) {
  $scope.students = data;
  $scope.$apply();
});

Alternatively, you can use:


$http({
  method: 'GET',
  url: '/api/students'
}).then(function(data) {
  $scope.$apply(function() {
    $scope.students = data;
  });
});

Referencing the $apply documentation:

The $apply() function is utilized to run an expression in AngularJS from outside of the AngularJS framework.

Answer №2

If you encounter an issue, consider adjusting the value of $scope.students directly in this manner:

/// <reference path="../angular.js" />
var stucontrollers = angular.module("stucontrollers", []);
stucontrollers.controller("GetStudentsList",
    function GetStudentsList($scope, $http) {
    $scope.students = [{Id: 1, FirstName: "John"}];
});

After making this change, one of two scenarios may occur:

a) If you can see John in the list: it indicates that ng-controller and ng-repeat are functioning properly. The issue might lie within retrieving the data. To troubleshoot further, try outputting your response using console.log.

b) If John is not visible in the list: there could be a problem even before the request is made.

Answer №3

My solution to the problem was successful, you may want to give it a try :

/// <reference path="../angular.js" />
var stucontrollers = angular.module("stucontrollers", []);
stucontrollers.controller("GetStudentsList",
    function GetStudentsList($scope, $http,$rootScope) {
    $http({
        method: 'GET',
        url: '/api/students'
    }).then(function(data) {
    $rootScope.$apply(function(){
        $scope.students = data;
    });
  });
});

Answer №4

Give this a shot:

    /// <reference path="../angular.js" />
    var studentControllers = angular.module("studentControllers", []);
    studentControllers.controller("FetchStudentList",
    function FetchStudentList($scope, $http) {
    $http({
        method: 'GET',
        url: '/api/students'
    }).then(function(response) {
        $scope.students = 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

Using MongoDB's MapReduce feature along with the Date and % operator

I am encountering an issue with a Python script that I am using to aggregate large collections into smaller pieces and group them by timestamp. map = Code("function(number) {" "emit({" "ts : new Date(new Date((this.ts - (this.ts % (60 * number ...

Update the CSS styling of a parent div based on the active state of specific child divs

I have a class with 4 distinct columns. div class="mainContent"> <div class="left-Col-1" *ngIf="data-1"> </div> <div class="left-Col-2" *ngIf="!data-1"> ...

#Error 500 encountered in a basic Ruby on Rails and AngularJS collaboration

Thanks to everyone for taking the time to assist me with this problem. As a newcomer to Ruby, the solution may be quite simple. I have developed an API that facilitates communication between Ruby and Angularjs. Here is the API: class EntriesController < ...

How can we leverage the nullish coalescing operator (`??`) when destructuring object properties?

When working with ReactJS, I often find myself using a common pattern of destructuring props: export default function Example({ ExampleProps }) { const { content, title, date, featuredImage, author, tags, } = ExampleProps || {}; ...

Exploring AngularJS 1.5+ Unit Testing: Harnessing the Power of $componentController and Embracing Double

I'm currently encountering an issue with my testing code. They say a picture is worth a thousand words, so here's an example. describe('Initialization', () => { let $componentController, scope; beforeEach(inject((_$componen ...

Issue with installing vscode-ripgrep during VSCode build/run process

After attempting to build and run VSCode on my Ubuntu 17.10 by following the instructions from this guide: https://github.com/Microsoft/vscode/wiki/How-to-Contribute#build-and-run, I encountered an issue when installing dependencies using yarn. The error m ...

Encountering a problem with AngularJS interpolation while trying to parse an

Just getting started with AngularJS. I am working on developing a single page application to showcase my comic slides/pages one at a time. The data is being fetched from a JSON file and that part seems to be working fine. However, I am encountering errors ...

Create a function that adds a new div element with a one-of-a-kind identification when

I am currently developing a web application on www.firstusadata.com/cash_flow_test/. The functionality involves two buttons that add products and vendors dynamically. However, the issue I'm facing is that the appended divs do not have unique IDs, maki ...

Tips on automatically populating a textbox without the need for a button click

I am currently using the following code: <input type="text" value="<?php echo empty($this->session->store['actual_info']['actual_total_marketing_budget']) ? '' : $this->session->store['actual_info' ...

show the day of the week for a specific date saved in a MongoDB database

I need to create a report showing the total number of purchases for each day in the past week, formatted like this: { "sunday":30, "monday":20, ... } Each purchase in the database is structured as follows: { _id: 603fcb ...

Every time I attempt to execute mupx deploy, an error message appears

issue in console shubhabrata@shubhabrata-VirtualBox:~/Meteor/myapp$ mupx deploy Meteor Up: Advancing Meteor Deployments for Production Configuration file : mup.json Settings file : settings.json “ Discover Kadira! A powerful tool to monitor yo ...

Whenever I attempt to start the server using npm run server, I encounter the following error message: "Error: Unable to locate module './config/db'"

This is the server.jsx file I'm working with now: Take a look at my server.jsx file Also, here is the bd.jsx file located in the config folder: Check out the db.jsx file Let me show you the structure of my folders as well: Explore my folder structur ...

Establishing a minimum date based on the date selected in the earlier datepicker

My webpage features two date pickers, one for startdate and the other for enddate. The current setup requires that the second datepicker remains inactive until a change is made to the first one. The datepicker for enddate is initially set with the startin ...

Define JSON as writeable: 'Error not caught'

I'm facing an issue with a read/write error in my JavaScript code because the JSON file seems to be set as read-only ('Uncaught TypeError: Cannot assign to read only property'). How can I change it to writable? Should I make changes in the J ...

Encountered an issue with instafeed.js due to CORS policy restrictions

Trying to implement an API that provides JSON data for use in a function. Required Imports: Importing Jquery, instafeed.min.js, and the API (instant-tokens.com). <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js& ...

Allow the words to seamlessly transition back and forth between columns in a continuous cycle

Currently, I am attempting to showcase a large text in a format similar to a book. Each "page" has designated width and height, with content displayed over two columns: left and right. In this layout, page 1 is on the left, page 2 on the right, page 3 on t ...

Automatically tally up the pages and showcase the page numbers for seamless printing

I've been tackling a challenge in my Vue.js application, specifically with generating invoices and accurately numbering the pages. An issue arose when printing the invoice – each page was labeled "Page 1 of 20" irrespective of its actual position in ...

Creating a function that writes to a file by utilizing the data input from

After running the provided code snippet, it successfully works in a standalone project. However, I am interested in making modifications to replace the variable "sample_text" with an output that is displayed in the terminal instead of being hardcoded int ...

The event OT.Publisher.onStreamAvailableError is triggered when the media stream is unexpectedly aborted,

Currently, I am experimenting with Opentok using Node.js. My goal is to enable one-to-one video chats between users utilizing Tokbox's services. Surprisingly, the functionality works flawlessly in Chrome but encounters issues in Firefox. An error mes ...

Connect ngOptions to an array beyond the current scope

Can the ngOptions be bound to a value that is not within the $scope? I have enums that will be generated as JavaScript code. These enums are not currently part of "the angular domain", but I want to bind an ngOptions to one of the arrays without manually ...