Having trouble displaying the filtered item when using the limitTo function in conjunction with ng-show and ng-repeat

I have a collection of well-known locations, each location includes a tour array with 20 elements - representing the number of tours available at that particular location. For example, 'Egypt' has 20 tours showcasing its various attractions. However, some tours do not include any accommodation options, while others do.

<div ng-repeat="tour in place.tours | limitTo:3" ng-show="tour.hotels.length != 0">
  <li>
    <a ng-repeat="hName in tour.hotels"> {{hName.name}}
    </a>
  </li>
 </div>

In the first ng-repeat, I only display tours that have a hotel available (with 1 hotel) using ng-show. In the second ng-repeat, I list out the names of hotels from the hotels array.

Ultimately, I extract all hotel names from tours that offer accommodations by using these two ng-repeat.

While everything is functioning as intended, I now want to display only the first 3 hotel names from the list obtained in the second ng-repeat. Adding limitTo:3 in the first ng-repeat does not show the first 3 hotel names because those elements are already hidden if no hotel is present, although the indexes persist!

I came across a related discussion on this topic but it didn't provide a solution Using ng-repeat and limitTo to limit the number of visible items displayed

How can I specifically showcase only the first 3 hotel names from the filtered list of hotels? What am I overlooking in my approach?

Answer №1

Try this code snippet to filter tours based on the number of hotels:

<!doctype html>
<html lang="en>
<head>
  <meta charset="UTF-8">
  <title>Example - hotel-filter-production</title>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
</head>
<body ng-app="">
  <div ng-init="tours = [
    {name:'A', hotels:[{name:'AA'},{name:'AB'}]},
    {name:'B', hotels:[{name:'AA'},{name:'AB'}]},
    {name:'D', hotels:[{name:'AA'}]},
    {name:'E', hotels:[{name:'AA'},{name:'AB'}]},
    {name:'F', hotels:[{name:'AA'},{name:'AB'}]},
    {name:'G', hotels:[{name:'AA'},{name:'AB'}]},
    {name:'NONEA'},
    {name:'NONEB'}
    ]"></div>
    <div ng-repeat="tour in tours | filter: { hotels: []}">
    Tour name : {{tour.name}} {{tour.hotels.length}} <br>
    <div ng-repeat="hotel in tour.hotels">
      Hotel Name : {{hotel.name}}
      <br/>
    </div>
    <br>
  </div>
</html>

Check out the live demo here.

Answer №2

To achieve the desired outcome, it is important to apply a custom filter first before setting any limitations.

JS

  $scope.filterFn = function(tour)
    {
        // Implement necessary checks

        if(tour.hotels.length > 0)
        {
            return true; // Include in results
        }

        return false; // Exclude from results
    };

HTML

<div ng-repeat="tour in place.tours | filter:filterFn | limitTo:3">

Answer №3

It seems like there might be some confusion in your question, but if you're looking to display the initial 3 hotels for EVERY tour, consider using the limitTo filter within the second ng-repeat loop.

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

Having trouble with a JQuery ajax post to a PHP server - receiving the error message "SyntaxError: Unexpected token < in JSON at position 0"

I am attempting to transmit json data to a server and retrieve a json response. My code is displayed below: JS: function login() { console.log("clicked"); //gather form values into variables var email = $("#email").val(); var password = $("#password"). ...

Turning plain text into functional HTML using React.js

After receiving data from an API that includes HTML, I encountered an issue where the HTML tags were being transformed into strings instead of being rendered as actual HTML when displayed in my code. I've done some research and came across the dange ...

The second instance of a React Paginate on the same page remains static and does not trigger a

Having a bit of trouble with using react-paginate for pagination - I have two instances on the same page (one at the top and one at the bottom). When a new prop is received, only the top instance gets re-rendered. The code seems to be working fine as all ...

Guide on transforming an array into a collection of objects

Could someone please help me with converting this array? const myArr = ['lorem', 'ipsum', 'dolor', 'sit', 'amet'] I want to transform it into an object structure like this: { lorem:{ ipsum:{ ...

CSS styling does not apply to HTML elements that are dynamically created using JavaScript

A script containing dynamic HTML content is sourced from an external website, injected by RSS feeds. To access the content directly, visit this link. The script needs to be wrapped around HTML tags for front-end display. For example: <div>http://fe ...

Is there a way for me to obtain a selection of 20 random items from this JSON data

When working with my JSON data using Myjson.slice(1, 20), I encountered a situation where I needed to extract only 20 items from a dataset that had a length of 2624. In the code snippet provided, I attempted to use the slice method but struggled to differe ...

Order child property in AngularJSWe are sorting properties in

Greetings! I am in search of a way to arrange an angular list according to a specific child property. Here is the model that I currently have: $scope.data = [{name:"John",type:{talent:"genius",val:99}}, {name:"Paul",type:{talent:"genius", ...

Having trouble accessing a custom factory within a directive in Angular using TypeScript

Having some trouble with my injected storageService. When trying to access it in the link function using this.storageService, I'm getting an undefined error. Any assistance on this issue would be greatly appreciated. module App.Directive { import ...

Switching the background color of a button on click and resetting the color of any previously clicked buttons (a total of 8

I'm struggling to implement a feature where only one button out of a column of 8 should be toggled yellow at a time, while the rest remain default green. Unfortunately, I can't seem to get the function to execute on click, as none of the colors a ...

Transforming an array into an object by applying filtering, prioritization, and minimizing loops

Consider the following array: const array = [{ typeName: 'welcome', orientation: 'landscape', languageId: 1, value: 'Welcome' }, { typeName: 'welcome', orientation: 'landscape', languageId: 2, value: & ...

What are some strategies to avoid triggering onBlur events for sibling or related components?

I've been working on a complex autocomplete feature, and the requirement is that when the input field is focused, the result box should be displayed. However, when the user moves to the next input, clicks anywhere on the screen, or presses Escape, the ...

What is the best way to access and retrieve URL parameters within AngularJS?

I'm currently working on a blog project using AngularJS. The main page is connected to an external service that provides an array of all the articles I've written. Each post is displayed with a shortened version on the homepage, along with a "rea ...

Converting canvas illustrations into HTML files

I am in the process of creating a drawing application that will be able to export into HTML/CSS/JavaScript. I plan to use this tutorial as a foundation for the drawing functionality. My goal is to take all the rectangles within the this.shapes = [] array a ...

Tips for creating gaps between list items in a collapsible navbar

I am attempting to add spacing between the li items in my collapsible navbar However, the issue arises when I slightly minimize the browser window, causing the navbar to collapse incorrectly. See image below: https://i.sstatic.net/TdKb4.png Below is t ...

Each time a new client connects, socket.io replicates the information

Exploring Node.js and socket.io for the first time, I have developed a small application where a table is meant to be displayed in real-time via socket.io when a function is triggered through a websocket (function triggers an "emit"). However, I'm fac ...

Adding Gridster to a WordPress theme

I am having an issue with implementing Gridster into my WordPress plugin. Despite correctly loading the necessary files from the folder, it does not seem to work. function add_my_stylesheet() { wp_enqueue_style( 'myCSS', plugins_url( ' ...

Is it possible to implement a custom sign-in form for AWS Cognito?

Is it possible to replace the AWS Cognito hosted UI with a custom form in my Next.js app that utilizes AWS Cognito for authentication? import { Domain } from "@material-ui/icons"; import NextAuth from "next-auth"; import Providers fro ...

Why does jQuery.get() keep altering the URL I'm using?

I encountered an issue with the code snippet below, where I attempted to fetch a resource using an Ajax jQuery call. $.get({ url: "http://jennifer-lawrence/mygirl/FreeTonight.php", type: "GET", dataType: "json", ...

Incorporate user input into Alert Dialog Boxes

Would you be able to assist me in displaying the input value from the "email" field in my alert box? The code seems to be working fine, but I'm having trouble getting the alert box to show the email form value. I decided to use Bootstrap for som ...

The application is functional, however, the initial controller within is experiencing difficulties

Setting up a controller in my application based on a tutorial. The first two divs are displaying correctly but the ContraAss controller is not rendering and only shows {{info}}. What am I missing here? (NB. Probably something simple, but with limited exper ...