Issue with ng-repeat not rendering JSON data properly

Can someone help me understand why ng-repeat is behaving differently in my case? When I use ng-repeat with the jsonFile, it prints to the table as expected, but when I try using it with problems, it doesn't print anything. The JSON data is usually loaded from a local directory, but for the sake of CodePen, I included a small JSON variable.

Just to clarify, changing $scope.jsonFile to $scope.problems does work. However, my issue arises when parsing through user input and attempting to display the data afterward. Even though console.log() shows identical outputs for both the original json and parsed json, it still doesn't display properly.

I have inspected the source code, and both $scopes are printed to the console.

https://codepen.io/dneverson/pen/BvLyqW

Main.js

let app = angular.module("MyApp", []);

app.controller("MyCtrl", function($scope, $http){

  // #################### GLOBALS ####################
  $scope.logTime = {};
  // #################### FUNCTIONS ##################

  //GET JSON FILE
  $http.get('./data/Problems2.json').then(function(response) {
    $scope.jsonFile =  response.data;
    console.log($scope.jsonFile);
  });
  
  // Rest of the main.js file functions...

Index.html

<!DOCTYPE html>
<html lang="en" dir="ltr" ng-app="MyApp">

  <head>
      <!-- Head section content goes here -->
  </head>

  <body ng-controller="MyCtrl">
      <!-- Body section content goes here -->
  </body>

</html>

Main.css

Your CSS styles go here...

Problems2.json

Your JSON data goes here...

Answer №1

It may seem unconventional, but the issue lies in loading up $scope.problems outside of Angular's digest cycle. This causes Angular to not update the view with search results, even though the values are present when you console.log($scope.problems). To address this without restructuring your code, you need to wrap the section where you add values to $scope.problems in a $scope.$apply() block within your $scope.searchJSON() function. This alerts Angular that you have modified the $scope.problems collection and will display the search results in your view:

if (found) {
    $scope.$apply(() => {
        found.forEach((i) => {
          $scope.problems.push(JSON.parse(i));
        });
    });
  }

Answer №2

I utilized your codepen data to successfully display it.

<table class="table table-hover">
    <thead>
      <tr>
        <th>ID</th>
        <th>Description</th>
        <th>Weight</th>
        <th></th>
      </tr>
    </thead>
    <tbody>
      <tr class="tblRow" ng-repeat="problem in problems | orderBy:'-Weight' track by $index"  " ng-class="{'color-grey': problem.Weight === 0, 'color-blue': problem.Weight <= 1 && problem.Weight > 0 , 'color-green': problem.Weight >= 1}">
        <td>{{problem.ID}}</td>
        <td>{{problem.Description}}</td>
        <td>{{problem.Weight}}</td>
        <td class="rowbtn"><button class="btn btn-success" ng-click="addProblem(problem)" style="display:none;">Add</button></td>
      </tr>
    </tbody>
  </table>

and here is the available data:

 $scope.problems= [
{"ID": "A0103","Description": "Typhoid pneumonia","Weight": 0.205},
{"ID": "A0104","Description": "Typhoid arthritis","Weight": 0.51},
{"ID": "A0105","Description": "Typhoid osteomyelitis","Weight": 0.51},
{"ID": "A021","Description": "Salmonella sepsis","Weight": 0.548},
{"ID": "A0222","Description": "Salmonella pneumonia","Weight": 0.205},
{"ID": "A0223","Description": "Salmonella arthritis","Weight": 0.51},
{"ID": "A0224","Description": "Salmonella osteomyelitis","Weight": 0.51},
{"ID": "A065","Description": "Amebic lung abscess","Weight": 0.205},
{"ID": "A072","Description": "Cryptosporidiosis","Weight": 0.451},
{"ID": "A202","Description": "Pneumonic plague","Weight": 0.205},
{"ID": "A207","Description": "Septicemic plague","Weight": 0.548},
{"ID": "A212","Description": "Pulmonary tularemia","Weight": 0.205}
];

Please verify your data post Http call. When does the HTTP call occur? Ensure you retrieve the data after your controller has been loaded.

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

Steps to resolve the error message 'Argument of type 'number' is not assignable to parameter of type 'string | RegExp':

Is there a way to prevent users from using special symbols or having blank spaces without any characters in my form? I encountered an error when trying to implement this in my FormGroup Validator, which displayed the message 'Argument of type 'nu ...

Using Angular's ng-repeat directive to iterate over an array from JavaScript

I am attempting to display an array in the HTML HTML: <div class="personWrapper" ng-repeat="message in messages"> <p>{{message}}</p> </div> JS: var app = angular.module('matcherApp', [ "ngRoute", "ngStorage" ] ...

Implementing a timed delay before assigning a class in the state

I am trying to implement a delay before applying for a new class. This is my current situation const [isDone, setIsDone] = useState<boolean>(false); Within a method, I have the following code snippet const myMethod = () => { .... .... se ...

Complete asset management system for node with using connect/express and broccoli

Admittedly, I am a beginner when it comes to node. My background includes experience with ASP.NET, PHP, and Django before diving into node development. However, I have found working with node to be a refreshing change. Although this issue is not solely rel ...

Master the art of directing your attention to a list element with ease using the tab function and jQuery

I've been tasked with creating a questionnaire for a client. They want the current active question to be displayed at 100% opacity, while the inactive questions should be at 20% opacity. Currently, when the page loads, all questions are dimmed to 20% ...

Avoid invoking the throttle function from lodash

I am currently facing an issue in my React project with a throttle function from lodash. The requirement is that the function should not be executed if the length of the parameter value is zero. I have tried checking the length of the value and using thro ...

Looking for a condensed version of my app script to optimize speed and efficiency

In my script, users input data and run the script by clicking a button. The script then appends the data to two different tabs and clears the data entry tab. However, I encountered an issue where I had to manually hard code each cell for appending, causi ...

NPM TypeORM is throwing the error message "Duplicate migrations" when changes are made to a migration file

Recently, I made a modification to an existing table by adding a new column using the command npm run migration:generate <filename>. Unfortunately, I realized later on that I had misspelled the column name and needed to correct it (showComission -&g ...

Getting the specific information you need from a JSON object in Angular 2

Struggling to extract specific data from a JSON file with nested objects like this: { "results" : [ { "address_components" : [ { "long_name" : "277", "short_name" : "277", "types" : [ "street_number" ] ...

Monitor modifications to documents and their respective sub-collections in Firebase Cloud Functions

Is it possible to run a function when there is a change in either a document within the parent collection or a document within one of its subcollections? I have tried using the code provided in the Firebase documentation, but it only triggers when a docume ...

What is the best way to transfer information between two HTML pages in AngularJS using a factory or service?

Can someone help me figure out how to transfer data from one HTML page to another by clicking on a specific table row? I've been struggling to send the information successfully. ...

Element.html() call leads to erratic image results

For this question, there are two key components to understand Statement of the Problem GetProdImage.cs //Retrieving image from database based on id int id = Page.RouteData.Values["prod_id"]; Controller controller = new Controller(); DBContext context = ...

arranging a div after it has undergone rotation

I have an idea to create a div containing three texts, rotate it, and place it in a fixed position on the page. My goal is to make sure it fits perfectly on the screen. To achieve this, I initially created a div with height and width that were the opposit ...

Tips for navigating the material ui Expanded attribute within the Expansion Panel

After looking at the image provided through this link: https://i.stack.imgur.com/kvELU.png I was faced with the task of making the expansion panel, specifically when it is active, take up 100% of its current Div space. While setting height: 100% did achi ...

Why won't both routes for Sequelize model querying work simultaneously?

Currently, I am experimenting with different routes in Express while utilizing Sequelize to create my models. I have established two models that function independently of one another. However, I am aiming to have them both operational simultaneously. A sea ...

Understanding Aspect Ratios in CSS for Div Containers and their Components

I am crafting an HTML5 game without the use of canvas and aiming to maintain a 16:9 aspect ratio within my div. Thanks to javascript, achieving this is straightforward and it functions flawlessly. However, the elements inside the div occasionally appear to ...

Is there a way to collapse an element by clicking either the content inside the div or the button within the div?

Is there a way to make a button within a newly activated div close it? The existing code seems to have issues with this functionality, and adding new rules or functions has not solved the problem. Any assistance with fixing this issue using vanilla JavaScr ...

Using JavaScript ES6, we can access a specific array nested within a JSON array and loop through its elements by utilizing the

I have retrieved a JSON data from this link "response": [{ "id": "1", "title": "Star Wars", "project": [ "Star Wars Proj1", "Star Wars Proj2", "Star Wars Proj3", "Star Wars Proj4" ] }, { "id": "2", "titl ...

Which method is more effective: utilizing AJAX to retrieve page elements, or just toggling their visibility?

When it comes to web development, particularly in jQuery, should I preload my page and use jQuery to manipulate the DOM, or should I do it the other way around? This debate involves: <div id="item1" ></div> <div id="item2"></div> ...

Display or Conceal Content Depending on the Button's Status

I am currently working on implementing an accordion style button for a project. I have configured my component to hide the list when the button is clicked, but I am encountering an issue where the list does not reappear. Additionally, I would like to inc ...