AngularJS generates content based on the selected room list

Hello, I am just starting out with angularjs and need some guidance. I have a json data set called selectedRoomList, and I want to generate text based on this data. To display the information in a spinner, I am using nested ng-repeat loops. The challenge is that when the value changes, I need to present the selected room list in text form. For example, if I select two single rooms and one double room, it should be displayed as 2SGL,1DBL. This task is proving to be quite tricky for me, so I would greatly appreciate any help or solutions offered.

"roomTypes" : [{
        "type" : "Deluxe",
        "Deluxe" : [{
                "id" : "",
                "name": "Deluxe",
                "roomCategory" : "Single",
                "maxOccupancy" : 2,
                "childAllowed" : true,      
                "number" : 0
        },
        {
                "id" : "",
                "name": "Deluxe",
                "roomCategory" : "Double",
                "maxOccupancy" : 3,
                "childAllowed" : true,
                "number" : 0        

        },
        ...

In my HTML code below, I use ng-repeat to display different room types:

header :Deluxe: 
label : Single  spinner : value :number 

<div ng-repeat="room in roomTypes">
    <h5 style="color:#ff7043;">{{::$eval('messages.webapp.itinerary.hotel.roomType.'+room.type.toUpperCase())}}</h5>
        <div class="form-group col-md-3 col-xs-4" ng-repeat="roomCat in room[room.type]">
            <label class="col-md-12 col-xs-12">{{::$eval('messages.webapp.itinerary.hotel.changeRoom.'+roomCat.roomCategory.toUpperCase())}}</label>
            <div touch-spin ng-model="roomCat.number"></div>
        </div>
</div>

To create the required text output like 2SGL,1DBL, I've implemented the following function:

$scope.getMultipleRoomList = function(multiple){
    var multipleRoom=multiple;
    var numSignle;
    var room='';
    console.log('Hello Welcome To',numSignle);
    multipleRoom.forEach(function(item,idx){
        var roomType=item;
        roomType[item.type].forEach(function(item1,idx1){

            if(item1.number!=0){
                console.log(numSingle);
                if(item1.roomCategory.toUpperCase()=='SINGLE'){
                    room=room+item1.number+'SGL,';
                }
                else if(item1.roomCategory.toUpperCase()=='DOUBLE'){
                    room=room+item1.number+'DBL,';
                }
                else if(item1.roomCategory.toUpperCase()=='TRIPLE'){
                    room=room+item1.number+'TRPL,';
                }
                else if(item1.roomCategory.toUpperCase()=='TWIN'){
                    room=room+item1.number+'TWN,';
                }
            }
        });

    });
    room = room.replace(/(^,)|(,$)/g, "");
    return room;
}; 

Whenever there is a change in the spinner reference, the above function is triggered. However, using the variable numSingle inside forEach causes an error.

Answer №1

I'm not entirely clear on your exact needs, but a solution similar to this might suffice:

var roomCategories = {
  single: 'SGL',
  double: 'DBL',
  triple: 'TRPL',
  twin: 'TWN'
}

$scope.getMultipleRoomList = function (roomTypes) {
  var roomLabels = [];
  roomTypes.forEach(function (roomType) {
    roomType[roomType.type].forEach(function (item) {
      if (item.number > 0) {
        roomLabels.push(item.number + roomCategories[item.roomCategory.toLowerCase()])
      }
    });
  });
  return roomLabels.join(', ');
};

numSingle may be causing an error due to the misspelling as numSignle

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

Utilize PowerShell to access JSON fields by name through converting a string to JSON

How can I retrieve the value of $body.uuid? Here is my attempt: $body = @" { "uuid": "Test07", "subject": "Template07-Subject", } "@ $bodyJSON = ConvertTo-Json $body Write-Host $bodyJSON Write-Host "uuid=$($bodyJSON.uuid)" Write-Host "uuid=$($body ...

What is the method to retrieve JSON data from a URL and showcase the content on a JavaScript page?

I am currently developing a custom MS Teams application and I am facing an issue with fetching JSON data from a URL to display its contents later. Unfortunately, the fetch operation is failing. My objective is to retrieve a list of data from a specified UR ...

Retrieving the data-id attribute from dynamically rendered div elements

How can I modify my checkPair function to retrieve the data-id attribute when clicking on a dynamically created card? Currently, I am encountering an error stating "The name 'getAttribute' could not be found." function createHTMLElementFromHtml( ...

Explaining the jQuery $.post method

After a thorough search, I finally discovered the importance of adding return false; at the end of my JQuery code for posting data. Without it, my code wasn't functioning as expected. As a beginner in JQuery, I would appreciate some insights into the ...

Manage the visibility state of an ng-show within a specific element loop

I am currently generating a dynamic list of actions within my form. For example, save, approve, reject. When one of these actions is clicked, I want a spinner to appear within that specific button until I receive a successful response from the server. Bel ...

Python encountering an issue with parsing JSON data: json.decoder.JSONDecodeError

I recently encountered an issue where I used Insomnia to send a JSON file ('json_information') to my Django app. { "company": 2, "value": 0.15, "date": "2020-01-01", "default": "False", ...

Implementing the map function in ReactJS to showcase data on the user interface

I seem to be facing an issue while attempting to utilize an array of data to display a <ul> element. Despite the console.log's working correctly in the code provided below, the list items fail to show up. <ul className="comments"&g ...

Sending personalized list attributes through JSON to JavaScript in ASP.NET

Below is a custom list I created for pagination of my results: public class PagedList<T> : List<T> { public int PageIndex { get; set; } public bool HasNextPage { get; set; } // ... } I aim to pass this list via JSON to the View: ...

Problem with using Twitter Bootstrap in IE11 when Browser Profile Enterprise is enabled

I am facing an issue with a Bootstrap 3 web page. Some machines have IE configured to load intranet pages in Enterprise profile mode, while others have the default Desktop profile set in IE11. This configuration has caused the layout to break completely. ...

Ways to display the data within a BLOB object

On this page, the user is showcasing a table with three columns - tipo_esame (string), data_esame (string), and uri (BLOB). const archiveItems = this.state.archive.map((archive, i) => { return ( <tr key={archive.hash_referral}> <td ...

Is there a way to verify the content of a span and automatically guide the user elsewhere if it meets certain criteria?

Currently, I am facing an issue with adding Google authentication to my website as the redirect function is not working properly. As a solution, I plan to implement manual redirection using JavaScript in case the value of the span element is <span id= ...

Incorporate different courses tailored to the specific job role

https://i.stack.imgur.com/iGwxB.jpg I am interested in dynamically applying different classes to elements based on their position within a list. To elaborate: I have a list containing six elements, and the third element in this list is assigned the class ...

React eliminates all white spaces

Presented here is a compilation of various span elements: <span>1</span> <span>2</span> <span>3</span> <span>4</span> <span>5</span> Accompanied by the CSS style for these elements: span{ bac ...

Ways to combine all similar key values into an array

Apologies if the question seems unclear. Essentially, I am dealing with an object structured as follows: [{"6":6.5},{"4":4.2},{"6":6.3}] My goal is to eliminate duplicate keys while preserving their values, and merge them into a single unique key, formin ...

JavaScript isn't functioning properly after UserControl is loaded via Ajax

Thank you, Stilgar for helping me solve my issue. I created a javascript file and placed all my code in it. After adding this file to the UserControl and retrieving the UserControl's html, I used $("#DivID").html(UserControlHTML). Now everything is wo ...

Keep the Bootstrap modal open while the JavaScript validation is running, and redirect the form action if the validation is successful

When trying to execute the submit event from a form, my code is supposed to keep the modal open if validation fails. However, for some reason, this functionality is not working as expected. var myForm = document.updteform; var condition = true; if ...

Guide to transmitting webcam feed from server to servlet

I am trying to display the webcam connected to my server in a servlet. I have come across suggestions to use getUserMedia();, however, this only captures the user's video webcam feed and not the server's. Is there a way to achieve this? My servl ...

Utilizing a template to refine a JSON object

Looking to mask JSON objects' properties and values based on a dynamic template for security purposes. It's akin to seeing the JSON objects through a veil that is revealed only at runtime. Let's consider this JSON object: { "id": "1", "f ...

Angular being called before being established

After spending a considerable amount of time working on AngularJS, I encountered an error stating that Angular is being used before it was defined. Despite watching several instructional videos and thoroughly reviewing the documentation, even with just the ...

Unable to correlate the response with the designated object

I'm currently facing an issue while attempting to utilize Angular4 HttpClient with an observable object that I've defined. My challenge lies in mapping the response to the designated object. The root of the problem appears to be related to my us ...