Tips for showcasing a collection using ng-repeat in AngularJS

I have a JSON data set that needs to be displayed in columns:

  {
   "2": [
         {
           "$id": "1",
           "serverId": 1622,
           "innCode": "PLOIKJ7",
           "propertyName": "Property 1",
          },
         {
           "$id": "2",
           "serverId": 1622,
           "innCode": "BHGTRWA",
           "propertyName": "Property 2",
          }
        ],
     "3": [
          {
            "$id": "3",
             "serverId": 1623,
             "innCode": "TGHRE#W",
             "propertyName": "Property 3",
           }
        ]
  }

I'm currently struggling to iterate through this using ng-repeat. Below is the basic template I have defined:

  <div ng-repeat="s in sets">
       <div class="panel panel-info">
            <div class="panel-heading"><span><bold>Server:&nbsp;{{s.serverNum}}</bold></span></div>
            <div class="panel-body">
                <div>
                  <input type="checkbox" value="all#" ng-click="doNothing($event)"/>Select All
                </div>
                <div class="divider">&nbsp;</div>
                <div ng-repeat="p in s.properties">
                   <label class="margin-right12">
                       <input type="checkbox"                                                                        name="property_{{p.innCode}}"
                          value="{{p.innCode}}" ng-click="doNothing($event)"/> <small>{{innCode}} - {{p.propertyName}}</small>
               </label>
            </div>
          </div>
        </div>
     </div>

Any tips or suggestions would be greatly appreciated!

Answer №1

Here is an example of how to achieve this:
In the controller

$scope.data = {
   "2": [
         {
           "$id": "1",
           "serverId": 1622,
           "innCode": "PLOIKJ7",
           "propertyName": "Property 1",
          },
         {
           "$id": "2",
           "serverId": 1622,
           "innCode": "BHGTRWA",
           "propertyName": "Property 2",
          }
        ],
     "3": [
          {
            "$id": "3",
             "serverId": 1623,
             "innCode": "TGHRE#W",
             "propertyName": "Property 3",
           }
        ]
  };

In the template

<div ng-controller="yourCntroName">
        <div ng-repeat="(key, val) in data">// This line will display all keys within your set, such as '2' and '3'
            <div ng-repeat="obj in val"> // The value associated with each key (e.g. '2' and '3') is an array, so another loop is needed.
                {{'$id = '+obj.$id+' ,'}}{{'serverId = '+obj.serverId}}
            </div>
        </div>
 </div>

Answer №2

If you need help with the built-in ng-repeat directive, you can find the documentation here.

Based on the information provided in the documentation, it seems like the right expression for your situation should be

ng-repeat="(key, value) in expression"
. You should replace expression with set in your code.

Eventually, your code might look something like this:

  <div ng-repeat="(count, servers) in sets">
    <div class="panel panel-info">
      <div class="panel-heading">
        <span><bold>Server:&nbsp;{{count}}</bold></span>
      </div>
      <div class="panel-body">
        <div>
          <input type="checkbox" value="all#" ng-click="doNothing($event)" />Select All
        </div>
        <div class="divider">&nbsp;</div>
        <div ng-repeat="server in servers">
          <label class="margin-right12">
            <input type="checkbox" name="property_{{server.innCode}}" value="{{server.innCode}}" ng-click="doNothing($event)" /> <small>{{server.innCode}} - {{server.propertyName}}</small>
          </label>
        </div>
      </div>
    </div>
  </div>

Your code could be improved further, but start by focusing on one thing at a time - taking the time to read the documentation is highly recommended.

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

Revisiting unions with TypeGraphQL

Here is the code snippet I'm working with: const retrieveUsers = ({ Model, options, }) => Model.find(options).catch((e) => { throw e; }); @ObjectType({ description: "User model" }) @Entity() export class UserModel extends BaseEnti ...

webpack - compile one TypeScript file separately (2 actions)

In summary... When my Vue files are combined with background.ts, webpack processes them to create bundled vue files along with background.js I'm unable to run the background.js script I expected background.js to only contain "console.log(' ...

Encounter a parameter validation error

Just a quick question. I have a JS function that takes a parameter as input. If the passed value happens to be NULL, I want to handle it accordingly. However, my limited experience with JS is making it difficult for me to use the correct syntax. Here' ...

Is it possible to modify the CSS produced by Bootstrap in an Angular application?

Just starting out with Angular and Bootstrap I have the following displayed in my browser: Browser Code shown through inspect and this is what I have in my code: <ng-template #newSlaVmData let-modal> <div class="modal-header moda ...

Discovering the location of form parameters and utilizing them in a Request

I am currently attempting to scrape data from using Request and Cheerio, but I am encountering difficulties when trying to submit search terms. It seems like the process of sending the search string and selected category during the post request is not cl ...

Ways to verify whether a string has already been hashed in Node.js utilizing crypto

I am currently working on an application that allows users to change their passwords. For this project, I am utilizing Node.js along with the mongoose and crypto libraries. To generate hashes for the passwords, I have implemented a hook into the model&ap ...

Issue with JQuery Promise: fail() being invoked before promise resolution

In my TypeScript code, I encountered a peculiar issue with a jQuery promise. The fail() function is being executed immediately, logging an error message to the console, despite the promise resolving successfully afterwards. Here is the code snippet: ...

Query in progress while window is about to close

I'm attempting to trigger a post query when the user exits the page. Here's the code snippet I am currently working with: <script type="text/javascript> window.onbeforeunload = function(){ var used = $('#identifier').val(); ...

Ensure accurate interpretation of CSS3 transform percentages on Android devices

tl;dr? Looking for a way to enable GPU acceleration on Android Chrome & default browser for the mechanism shown in the link below. UPDATE 2 (2014-01-13 13:25:30Z): As per bref.it's comment, the issue was resolved with Android 4.4 KitKat but my previo ...

A guide on extracting keys and values from a JSON object and saving them in an array with the useState hook in a React application

function Graph() { const [tcases, setCases] = useState([]); const [recovered, setRecovered] = useState([]); const [deaths, setDeaths] = useState([]); useEffect(() => { axios .get("https://disease.sh/v3/covid-19/historical/all?last ...

Retrieve the product of two disabled textboxes' values

I need to automatically calculate the total of two textboxes when either one is changed, but I want to prevent users from manually inputting values. Therefore, these 2 textboxes will be disabled and filled from a dropdown menu. Edit: When I change the val ...

Issue encountered when using zmq and express

I have been working on developing an API that retrieves information from a socket using zmq. The goal is to receive data from the socket and then send it as a response through my API. The code snippet below illustrates this process. [...] enclaveSocket. ...

Unable to display the content

Why isn't the text expanding when I click "see more"? Thanks XHTML: <div id="wrap"> <h1>Show/Hide Content</h1> <p> This code snippet demonstrates how to create a show/hide container with links, div eleme ...

What is the best way to display data in the User Interface when data is being received through the console in AngularJS?

I have created an HTML file and the corresponding controller logic for this page. I can see the data in the console, but it's not displaying on my UI. <div id="panelDemo14" class="panel panel-default" ng-controller="NoticeController"> < ...

Adding static JSON array data to the results received from an API call

Within my code snippet below, I am able to retrieve a JSON Response: respArray = [] respArray = respBody.classifiers respBody = respArray if (respBody.length > 0) { respBody = applyPagination(respBody, reqParams.filter, option ...

The ToDate must always be greater than or equal to the FromDate

I have two datepickers, one for the From date and the other for the To date. I want the To date to always be equal to or greater than the From date. I have attempted to solve this issue, but I have not been successful in finding the proper solution. $(d ...

Wrap the content with a div at the beginning and at the end

Hello, I am currently working on implementing the following structure: <div class="content"> <img src="/"> <img src="/"> <div class="slideshow"> <img src="/"><img src="/"><img src="/"></div> ...

The image is loaded correctly through the image picker, however, it is not displaying on the screen

When I click the button to pick an image from the gallery in this code, it is supposed to load the phone's gallery and display the selected image in the image component. Even though the image gets loaded properly (confirmed through test logs), it does ...

The postman is coming back empty-handed with a 200 status code

I am receiving a null value as a response with a 200 status code. I am expecting to see the profile details as the response, but instead it is showing a null value with no error status code in my Postman. I can't find any errors in my code. Why is it ...

Angular's alternative to jQuery deferred.always() callback

Utilizing the .always() callback function in jQuery allows us to manage responses, regardless of whether they are successful or not. Is there a similar functionality in AngularJS that serves the same purpose? //jQuery $.get( "test.php" ).always(function( ...