Leveraging ng-switch with ng-repeat in AngularJS to dynamically apply HTML based on conditions

I have a paginated list of video thumbnails that I want to showcase in a Bootstrap fluid grid. To achieve this, I am utilizing a nested ng-repeat loop to iterate through each list for pagination purposes. Within the inner loop, another ng-repeat is used to cycle through each video thumbnail in the subarray. The grid layout follows a 3x6 format, so whenever the index of the inner ng-repeat is a multiple of 5 (taking into account that $index begins at 0), my goal is to close the current fluid row and initiate a new one.

<div ng-repeat="thumbList in thumbLists">
    <div ng-repeat="thumb in thumbList" class="row-fluid">
        <div class="span2">
            <a href="{{ thumb.URL }}">
                <img src="{{ thumb.thumbnailURL }}" width="160" height="85" alt="" class="img-responsive">
            </a>
        </div>
        <!-- ng-switch? -->
    </div>
</div>

The arrays are populated using a REST service. When a user clicks on the 'next' button, a new array list is pushed onto the existing lists and an animation smoothly transitions across each 3x6 grid. The data structure is as follows:

$scope.thumbLists = [
    [{URL: url, thumbnailURL: thumburl}, ...],  // initial
    [{URL: url, thumbnailURL: thumburl}, ...],  // added when user clicks 'next'
    ... and so forth
];

Although everything is functioning correctly, I am uncertain about how to dynamically insert HTML to close a row and begin a new one once it reaches 6 thumbnails because they are provided in a single array format.

For instance, could I potentially incorporate something similar to the following within the commented ng-switch block:

<div ng-switch="$index">
    <div ng-switch-when="$index % 6 == 5">
</div>

I am working with the stable 1.0.8 release and need to ensure compatibility with IE8.

A temporary fix involves eliminating the left margin for elements that appear as the first item in their respective rows:

<div ng-repeat="thumbList in thumbLists">
    <div class="row-fluid">
        <div ng-repeat="thumb in thumbList" class="span2" ng-class="{nomargin: $index % 6 == 0}">            
            <a href="{{ thumb.URL }}">
                <img src="{{ thumb.thumbnailURL }}" width="160" height="85" alt="" class="img-responsive">
            </a>
        </div>
    </div>
</div>

Ultimately, I would like to explore a solution where I can conditionally add or remove HTML, possibly by incorporating a directive.

Answer №1

Have you considered using ng-grid? It could simplify your task by handling the details for you.

Check out ng-grid here

Answer №2

This code snippet is compatible with ng-switch. However, it may require some additional adjustments to prevent the unnecessary hidden span markup.


      <div ng-repeat="thumb in thumbList">
          <span ng-switch="$index % 5">
            <div class="row" ng-switch-when="0">
              <div class="col-sm-2"><img src="{{thumbList[$index+0].url}}" class="img-responsive"></div>
              <div class="col-sm-2"><img src="{{thumbList[$index+1].url}}" class="img-responsive"></div>
              <div class="col-sm-2"><img src="{{thumbList[$index+2].url}}" class="img-responsive"></div>
              <div class="col-sm-2"><img src="{{thumbList[$index+1].url}}" class="img-responsive"></div>
              <div class="col-sm-2"><img src="{{thumbList[$index+2].url}}" class="img-responsive"></div>
            </div>
          </span>
      </div>

Check out this link for more information!

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

Looking for a specific text on $location update in AngularJS

Is there a way in AngularJS to search the DOM for text after a new view is loaded? The filter almost does this, but I'm not interested in returning a new array of elements. For instance; html <div ng-view=""> <ul> &l ...

Oops! Issue: The mat-form-field is missing a MatFormFieldControl when referencing the API guide

I included the MatFormFieldModule in my code like so: import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppRoutingModule } from './app-routing.module'; ...

Executing a JavaScript function across multiple elements: A step-by-step guide

I recently came across this code snippet on w3schools.com: <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> * {box-sizing: border-box} body {font-family: Verdana, ...

Is the Spring MVC ModelAndView object being returned?

After clicking a link on a jsp page, I have a GET method that is instantiated as: HTML: <div class="panel accordion clearfix" id="dispdir"> <script type="text/javascript"> window.onload = function() { //showDirectorySe ...

Managing JSON communications in Scala Play Framework and forwarding them to AngularJS JavaScript

Working on the implementation of a library system using Play Framework and AngularJS. To search for a book in the library, the user enters a keyword value in the input field. This value is received by the controller from a GET request. The task is to searc ...

The nightmare of Parent-Child Inheritance in JQuery/CSS is a constant struggle

Having difficulty implementing specific JQuery effects into a Bootstrap framework due to its extensive CSS causing issues. Created a test file named testjquery.html connected to a stylesheet defining a hidden element and activating the fade in of this ele ...

Navigating intricate data structures within React

As a newcomer to React, I could use some assistance with a project I am working on. The application is similar to Slack, where users can create new teams and channels. However, I am encountering difficulties in managing the state of the data input throug ...

Implementing checkboxes for each API data in JavaScript

I am fairly new to this and I am currently working on a to-do list. I want to include a checkbox next to each item from the API to indicate whether it has been completed or not. <script type="text/javascript"> fetch('http://localhos ...

Conceal a plugin within a component from the main module of app.js

While this might be considered outdated, there are still many experienced front-end developers who have the knowledge to tackle it. I am attempting to avoid declaring a plugin in the main module of my application. Imagine I have structured the following ...

Clicking on a hyperlink within an Angular Material button does not prompt the browser to navigate to the linked page

Currently, I am utilizing Angular Material with AngularJS v1. Encountering issues with a simplistic menu bar while utilizing angular material. Below is the piece of HTML code representing the menu bar: <md-toolbar layout="row" class="md-whiteframe-z3" ...

Save the status of checkboxes in a JSON file using boolean values of true or false

When a user submits a form, I am retrieving the values of checkboxes and storing them as an array. The simplified form structure is as follows: <!-- gym_create.html - other input fields are omitted for brevity --> <form class="create-gym" role=" ...

What is the most effective way to incorporate the DOMContentloaded event listener into the document using nextJS?

I am working on integrating an HTML code snippet into my Next.js project. The snippet includes an external script with a createButton function. <div id="examplebtn"></div> <script type="text/javascript"> //<![ ...

Combining multiple arrays in Node.js to create a single JSON file

I'm exploring the world of nodejs and currently working on creating a Json parser that will pull data from a Json API, allow me to access specific data points (some of which will need transforming), and then save it to a Json file. I recently came ac ...

Error in Javascript chrome when trying to determine the length of an array

I am facing an unusual issue with the JavaScript console in Chrome. When I type the following code into the console: var numbers = new Array(["/php/.svn/tmp", "/php/.svn/props"]); it returns "undefined." This leads me to believe that 'numbers' ...

What could be causing the Express server to return an error despite everything being in order?

I am new to exploring express.js and attempting to create a basic sign-in example server. I have set up a database object with a users array containing objects, each with email and password properties. Despite using body-parser to convert the body into a j ...

Using the val() function on a select element can occasionally result in a null value

Having an issue with my select. For some reason, when I use $(".test").val(), it sporadically returns null. Can't seem to figure out what's causing this inconsistency. console.log($('.test').val()); <script src="https://ajax.googl ...

Using various jQuery autocomplete features on a single webpage

UPDATE I have observed that the dropdown elements following the initial one are not being populated correctly. .data( 'ui-autocomplete' )._renderItem = function( ul, item ) { return $( "<li></li>" ) .data( "i ...

Function for testing global variable stub in JavaScript

Currently, I am in the process of writing Unit tests for a React application. Within the page header, the tracking library 'mixpanel' is inserted between <script> tags as outlined in their documentation: . The documentation states that "Th ...

Tips for navigating a list of areas in JavaScript

Currently, I am in the process of learning Javascript and I have a query regarding browsing an area list using Javascript. Could someone kindly guide me on whether it is possible to achieve this, and if so, how? Below is the HTML code snippet I am workin ...

Sorting tables in Jquery with advanced filter options and seamless integration with an ajax pager

I've implemented a tablesorter library for sorting and filtering data in a table along with a plugin that allows me to paginate the table across multiple pages. Due to the increasing number of records in my table causing slow loading times (>60 se ...