Displaying data based on specific identifiers in AngularJS

How can I update information based on the unique ID provided in a JSON file. JSON:

{
  "hotels": [
  {
     "id" : 1,
     "name": "some hotel 1",
     "category" : [{
        "id" : 1,
        "hotel_id" : 1,
         "name"  : "Cat name 1",
         "bnb" : "yes",
         "simple" : "yes"
     }]
  },
   {
     "id" : 2,
     "name": "some hotel 2",
     "category" : [{
        "id" : 1,
        "hotel_id" : 2,
         "name"  : "Cat name 1",
         "bnb" : "yes",
         "simple" : "yes"
     }]
  }
  ]
}

Within my HTML, I have an ng-repeat as follows:

<p>Hotel names</p>
    <ul>
        <li ng-repeat="hotel in list.hotels">

            {{hotel.name}}

            <ul class="thumbnails">
                <p>Category</p>
                <li ng-repeat="cat in hotel.category">
                    {{cat.name}}
                </li>
            </ul>
        </li>
    </ul>

I am attempting to display data for one specific hotel from the JSON file. Is there a more efficient method than using something like {{hotel[0].name}}? Also, how can I implement a toggle button to switch between displaying data for hotels with ID 1 and ID 2 within the same section?

Appreciate any guidance you can offer.

Answer №1

Utilizing the ng-repeat function allows for creating links that display different hotels based on user clicks, as demonstrated in the following example or this sample.

To organize the hotels into categories, another implementation of ng-repeat can be utilized (not included in the provided demo).

angular.module('demoApp', [])
.controller('mainController', MainController);
  
function MainController() {

  this.hotels = [
  {
     "id" : 1,
     "name": "some hotel 1",
     "category" : [{
        "id" : 1,
        "hotel_id" : 1,
         "name"  : "Cat name 1",
         "bnb" : "yes",
         "simple" : "yes"
     }]
  },
   {
     "id" : 2,
     "name": "some hotel 2",
     "category" : [{
        "id" : 1,
        "hotel_id" : 2,
         "name"  : "Cat name 1",
         "bnb" : "yes",
         "simple" : "yes"
     }]
  }
  ];
this.selectedHotel = this.hotels[0];
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demoApp" ng-controller="mainController as mainCtrl">
  
  <a href="#" ng-repeat="hotel in mainCtrl.hotels" ng-click="mainCtrl.selectedHotel = hotel">{{hotel.name}}</a>
  
  <div>
    Hotel name: {{mainCtrl.selectedHotel.name}}
    Category: {{mainCtrl.selectedHotel.category}}
  </div>
</div>

Answer №2

In response to your inquiry, be sure to observe the addition of ng-if

<p>List of Hotel Names</p>
<ul>
    <li ng-repeat="hotel in list.hotels">

        {{hotel.name}}

        <ul class="thumbnails">
            <p>Category</p>
            <li ng-repeat="cat in hotel.categories" ng-if="cat.id === yourid">
                {{cat.name}}
            </li>
        </ul>
    </li>
</ul>

You can customize yourid by utilizing the current controller. Additionally, heed the advice from others not to use ng-repeat if you only intend to show a single element

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

What could be the reason behind Strapi v4 only displaying the initial 25 articles? Discussing Next.js and React

I've encountered a peculiar bug while working with Strapi v4. The technology stack being used is React and Next.js I've set up a dynamic pagination system with the format /page/[slug]. It's functioning almost perfectly, except for one majo ...

Resolving Logic Errors in PostMapping

My service contains a method that is able to save a fruit in all the stores it has. This method functions properly in the main method, but encounters issues when used with Postman. Upon testing with Postman, only one instance of the fruit is created instea ...

Tips for structuring JavaScript code within ASP.NET MVC projects

We're looking to enhance the functionality of a view page with some Ajax functions. This means that when a user clicks on a delete or insert button, an Action will be triggered to carry out a CRUD operation in the background, followed by refreshing th ...

Using angularjs ng-repeat in combination with owl-carousel

<div class="owl-carousel"> <div ng-repeat="items in itemlist"> <a href="series.html"><img ng-src="{{items.imageUrl}}" /></a> </div> <div> <a href="series.html><img src="http://p ...

Ways to Manage Null Values in JSON Using Swift

My application keeps crashing when trying to handle null JSON data. I've been struggling with this problem for a while now, and I believe you're the best person to help me resolve it. func downloadJsonWithURLJB() { let url=URL(string:"ht ...

How to Retrieve the Text Content of a Button When Clicked in a Button Group Handler

My goal is to create two button groups. When a button in the second group is clicked, I want to dynamically add a new button to the first group with the same label as the clicked button. Using var name = this.textContent works well when the click handler ...

What is the best way to send a URL to a component using a prop and HTML tag in order to separate the front end functionality?

Currently in the process of developing my first personal website using ReactJS, I typically focus on backend development. Recently, I have delved into the world of software systems and have found myself captivated by Domain Driven Design. Please forgive my ...

What could be causing the error when attempting to send an HttpResponse from a Django View function?

Trying to utilize Ajax, I'm attempting to call a Django View function from JavaScript code. The View function is expected to return an HttpResponse, which should then be printed out on the console. However, upon inspection of the console, it simply s ...

Unable to alter Mui input label color upon focus using theme.ts

In my next.js app, I'm facing an issue with changing the color of the label in a Material UI input field using Mui. Despite updating the theme.ts file to change the border bottom color and label color, only the border bottom color is being applied. T ...

Error Connecting to Database with Node.JS MySQL Module - ECONNRESET Issue

Attempting to establish a connection with my database using the mysql module has been quite the challenge. Each time I try, an error seems to pop up: read eCONNRESET There is problem. (The final part is from my console log, as seen below.) I've ruled ...

Inspecting the JSON data returned by an AJAX request

This snippet of code utilizes AJAX to check if a user exists in the database. The response confirms that the user exists: {"exists":true} However, there seems to be an issue at POINT 1 $.post('http://lajmetari.info/icb/modules/mod_facebook/tmpl/sea ...

Leveraging *ngFor to extract HTML content from ion-label

I've encountered an issue while using *ngFor in my HTML like this: <ion-slides #slides [options]="slideOpts"> <ion-slide class="numbers-wrapper" *ngFor="let questionNumber of numbers" (click)="clickQue ...

Is it common practice to provide a callback function as a parameter for an asynchronous function and then wrap it again?

app.js import test from "./asyncTest"; test().then((result)=>{ //handle my result }); asyncTest.js const test = async cb => { let data = await otherPromise(); let debounce = _.debounce(() => { fetch("https://jsonplaceholde ...

Position the caret after adding a new element in a content-editable div

I have a contenteditable div that contains various elements. My goal is to automatically create a new paragraph tag right after the element where the cursor is positioned when the user presses the enter key. Currently, I am able to insert the paragraph tag ...

Missing dots on owl carousel

Currently, I am working on a project that involves using the owlcarousel library in javascript. Everything was running smoothly until I encountered an issue. Although I have set the dots to true in the code, they are not appearing on the carousel. Below i ...

How can I create an interactive slideshow with Angular in the most effective way?

What is the most effective method for creating a dynamic slideshow using AngularJS 1.3? I am interested in developing one, and have attempted to use http://jquery.malsup.com/cycle2/ but encountered issues when integrating it with angular.js on the same p ...

Encountered an error of 'npm ERR! invalid semver' when attempting to release an npm package

npm ERR! code EBADSEMVER npm ERR! invalid semver: npm ERR! Check out the full log of this run here: I attempted to reinstall node and semver, but unfortunately it did not resolve the issue. ...

How can I properly define 'null' as a value when deserializing a Twitter stream JSON string in F#?

If anyone needs the record types, they are left below. My question is as follows: How can one write to a file a record type that can be null? The current method gives an error stating "The type 'Basic' does not have 'null' as a proper v ...

Using jQuery DataTable to fetch JSON data upon Document Loaded

I am struggling to implement a PHP script that returns JSON data to populate a DataTable. The PHP script 'api/exceptions_all.php' is as follows: <?php $select = "SELECT '', [FOR_PARTNER], [FOR_NAME] FROM [brokerage].[dbo].[for_ex ...

Unable to use 'ngFor' as it is not recognized as a property of ... in a mixed AngularJS and Angular environment

My AngularJS and Angular hybrid application is giving me trouble when I try to downgrade my Angular test.component. Every time I attempt it, I encounter the following error messages: Can't bind to 'ngFor' since it isn't a known pro ...