Exploring the power of Angular by implementing nested ng-repeat functionalities:

I am currently working on an ng-repeat feature to add items from the array (album array). Everything seems to be functioning correctly. However, I also have a colors array that should assign different background-colors to the card elements of the album array. Unfortunately, the final result is not as expected. I attempted to convert the colors array into an object within the same array but still encountered issues. Any assistance would be greatly appreciated. To see the code in action, you can visit this CodePen link. The color array should cycle back around to match the number of albums in the album array.

function MainController(albumSerivce, $filter) {
  'use strict';

  var ctrl = this;
  ctrl.albums = [];
  ctrl.arrayColor = ['red', 'blue', 'green', 'yellow'];
}
.green {
  background-color: rgb(75, 175, 79);
  padding: 10px;
}
.red {
  background-color: rgb(255, 86, 34);
  padding: 10px;
}
.blue {
  background-color: rgb(61, 121, 182);
  padding: 10px;
}
.yellow {
  background-color: rgb(255, 255, 0);
  padding: 10px;
}
<body ng-app="app">
  <div class="container-fluid" ng-controller="MainController as ctrl">
    <div class="albums-container" ng-repeat="album in ctrl.albums" ng-cloak>
      <div class="album {{color}}" ng-repeat="color in ctrl.arrayColor">
        <img class="image" ng-src="{{album.url}}" alt="" />
        <div class="title">{{album.title}}</div>
      </div>
    </div>
  </div>
</body>

I have also experimented with another approach, although it didn't yield the desired outcome.

<!-- Another attempt using custom classes and ng-if statements based on modulus -->
<div ng-class="album green" ng-if="$index%">
  <img class="image" ng-src="{{album.url}}" alt="" />
  <div class="title">{{album.title}}</div>
</div>
<div ng-class="album red" ng-if="$index%">
  <img class="image" ng-src="{{album.url}}" alt="" />
  <div class="title">{{album.title}}</div>
</div>
<div ng-class="album blue" ng-if="$index%">
  <img class="image" ng-src="{{album.url}}" alt="" />
  <div class="title">{{album.title}}</div>
</div>
<div ng-class="album yellow" ng-if="$index%">
  <img class="image" ng-src="{{album.url}}" alt="" />
  <div class="title">{{album.title}}</div>
</div>

Answer №1

If you're looking to avoid iterating through the color array, you can simply assign the class using an expression. Feel free to check out this CodePen for reference.

<div class="album {{ctrl.arrayColor[$index%ctrl.arrayColor.length]}}" >
        <img class="image" ng-src="{{album.url}}" alt="" />
        <div class="title">{{album.title}}</div>
</div>

Answer №2

Instead of iterating through the colorArray using a ng-repeat, utilize ngClass with an expression that selects one of your color classes. To cycle through them in order, you can use the expression albumIndex%colorArrayLength (index remainder array length) to get the correct index.

ng-class="colorArray[$index%colorArray.length]"

The variable $index will be automatically assigned by Angular to represent the current index of each iteration in ng-repeat (in this case, the album array).

angular.module("app",[]).controller("ctrl",function($scope){
  $scope.colorArray = ['green','red','blue','yellow'];
  $scope.albums =[{
    title:"Kitten 1",
    url:"https://placekitten.com/g/100/100"
  },
  {
    title:"Kitten 2",
    url:"https://placekitten.com/g/100/100"
  },
  {
    title:"Kitten 3",
    url:"https://placekitten.com/g/100/100"
  },
  {
    title:"Kitten 4",
    url:"https://placekitten.com/g/100/100"
  },
  {
    title:"Kitten 5",
    url:"https://placekitten.com/g/100/100"
  },
  {
    title:"Kitten 6",
    url:"https://placekitten.com/g/100/100"
  }];
});
#container{ display:flex; }
.album { flex: 1 1 0; }
.album img { max-width: 100%; }
.green {
  background-color: rgb(75, 175, 79);
  padding: 10px;
}
.red {
  background-color: rgb(255, 86, 34);
  padding: 10px;
}
.blue {
  background-color: rgb(61, 121, 182);
  padding: 10px;
}
.yellow {
  background-color: rgb(255, 255, 0);
  padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div id="container" ng-app="app" ng-controller="ctrl">
  <div class="album" ng-class="colorArray[$index%colorArray.length]" ng-repeat="album in albums">
    <img class="image" ng-src="{{album.url}}" alt="" />
    <div class="title">{{album.title}}</div>
  </div>
</div>

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

In ASP.NET MVC, use CSS styling specifically for Partial Views by encapsulating the styles within a `<style scoped>` tag

A new HTML attribute has emerged, known as scoped, however, it is currently only supported by Firefox. This attribute allows you to declare internal styles solely for the parent element. I am curious if it is feasible to replicate this functionality in AS ...

Interactive Tab content display

I'm working on a tabs component and I need Angular to only render and initialize the active tab instead of all tabs. Is there a way to achieve this? <my-tabs> <my-tab [tabTitle]="'Tab1'"> <some-component></some-co ...

After successfully sending a GET request to the API, the Next.js 13.4.3 website still does not reflect new posts added on the hosting platform

I am currently using Next.js version 13.4.3 in my app directory to create a blog site. However, I am facing an issue. When I run npm run build locally on my computer and then start with npm run start, the new posts are displayed normally after adding them ...

Is there a way to achieve a double background color effect in CSS while ensuring that the text is centered within the second background color element?

How can I achieve a layout similar to the one shown in this image: ul menu li tags Should I use two tags for each element? Here is an example: <ul class="menu"> <div class="outside"><li class="inside"><a href="#">Firefox</a ...

Tips for creating a Bootstrap table with a "table-bordered" style, fixed header, and scrollable body

How can I keep the table header fixed while allowing the body to scroll without breaking the table layout? I've tried using the CSS below, but it results in the width of the header columns being different from the width of the body columns. Any sugges ...

Trigger a series of functions upon clicking with ReactJS

Need some assistance with an alert message functionality. I have a button labeled Checkout, and when clicked, it should clear the cart and display an alert. At present, the individual functions work as expected - calling emptyCart() works fine, and calling ...

Transmit information from a comprehensive form using AJAX technology

I created a complex form with 30 fields, out of which 3 fields are repeated 10 times. Here's the code: <form id="artikelform" method="POST" name="controleartikelen" action=""> <table id="controle"> <tr><th>Maakartikel</ ...

Struggle with Firefox: Table-cell with Relative Positioning Not Acting as Parent

Upon investigation, I have come across a unique layout issue that seems to only affect Firefox. It appears that elements with display:table-cell; do not act as the positional parent for descendants with position:absolute;. It is surprising to discover th ...

Align and resize image using CSS styling

Seeking assistance on centering and cropping images using CSS. Tried implementing the technique from this specific article. However, experiencing inconsistencies in device UI output. Can someone shed light on this behavior? Scenario: The objective is t ...

Issue with Google Maps iFrame not loading when utilizing JavaScript variables in the "src" attribute

Currently, I am facing an issue with utilizing JavaScript variables containing GPS latitude and longitude values in the "src" attribute of an iFrame in an HTML file for displaying image EXIF data on a Google Maps iFrame. When I hardcode specific latitude ...

What is the best way to customize a div depending on the validation status of all reactive form fields within it?

I am facing a challenge with a rather complex form that contains multiple fields. Some of these fields are used to create logical blocks, and I would like to emphasize the surrounding div if any of these included fields are invalid. Can you suggest the bes ...

Enhance the sent server parameters by including extra options in fineuploader

I have successfully implemented file uploads using . Everything works perfectly. I am able to set parameters in the request object to send additional data to the server. However, when I try to add another parameter dynamically using the setParams function ...

The anchor tag is failing to register when placed inside a dynamically created table cell

I'm attempting to place an anchor tag within a cell of an HTML table. Here is the code I am using, but for some reason, the tag is not being identified and no hyperlink is displayed in that cell. Is there an issue with the syntax? $("#tranTbodyI ...

When a new marker is clicked on Google Maps, the previous Infowindow will automatically close

Here are some specific locations to consider: var places = [{ "id": 1, "ReferenceNumber": "52525252525", "Address" : "School" , "Latitude": "21.585486", "Longitude": & ...

What is the best way to direct users to an input field within a dynatree title?

I am currently utilizing Dynatree to display a tree view, and my goal is to focus on an input field within the dynatree title element. However, I am encountering an issue where the focus is being lost. My code attempts to address this problem but unfortun ...

Error: Attempting to create a Discord bot results in a TypeError because the property 'id' is undefined

While working on a basic Discord bot, I encountered an issue when running the -setcaps command. The error message I received was: TypeError: Cannot read property 'id' of undefined. I'm unsure about what might be causing this error. Any a ...

Customize each Picker.Item element in React Native with unique styles

How can I style individual Picker.Items beyond just changing the text color? Additionally, what other props can be used for a Picker.Item? I am aware of "key", "value", "label", and "color". Are there any additional props available? I want to customize o ...

What is the best way to interact with a html element using the onclick event in Selenium?

Struggling to find the xpath for a link on a webpage. The HTML code for the link is as follows: <td style="width: 50%; text-align: right; vertical-align: middle"> <img id="ctl00_ContentPlaceHolder1_RadGrid1_ctl00_ctl02_ctl00_AddRecord1" ...

Efficiently styling table Spans with styled components in React

Can anyone help me with a frustrating CSS problem I'm facing? I am trying to render these tags as spans, but they are not separating properly as shown in the image below. They appear stuck together and I can't figure out why. I am using styled co ...

Mapping various sets of latitudes and longitudes on Google Maps

I am working with multiple latitude and longitude coordinates. var latlngs = [ {lat:25.774252,lng:-80.190262}, {lat:18.466465,lng:-66.118292}, {lat:32.321384,lng:-64.757370}, {lat:25.774252,lng:-80.190262}, ]; The coordinates were ret ...