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

Centering an image (svg) vertically inside a link tag

I've been struggling to vertically center the config button (#config) and none of the options I've tried worked the way I wanted. Here is a link to my CodePen: http://codepen.io/fenwil/pen/ONRXwz Here is the crucial part of the code that need ...

Error: Unable to load Handlebars helper function

I am working on implementing a custom hbs helper in my Express.js application. However, I keep encountering an error message that says: Missing Helper "if_eq" The code for my page is as follows: <html> <head> <script src="javascript ...

Ways to modify the background images in doxygen

Currently, I am facing a challenge while customizing Doxygen's output and my main roadblock is the menu bar. To address this issue, I decided to generate custom CSS and HTML files provided by Doxygen by executing the command: doxygen -w html header. ...

Creating a customized list item design using Bootstrap 3 and incorporating div elements

I have designed a custom li element with Bootstrap 3, but I am looking to achieve something specific. . Here is my current setup- HTML- <ul class="list-group"> <li class="list-group-item" id="baal"> <div style="display: inlin ...

Ways to extract the coordinates for slices positioned around the circumference of a pie chart

Currently, I am working on designing a pie chart with D3 using d3.layout.pie(). The image resembles the one displayed below, but without the black dots. These dots were added manually in Photoshop to highlight an issue that I am facing. I am curious about ...

Error encountered: When trying to pass an event and two variables, the function e.preventDefault is not recognized as a valid

As a beginner in JS, I thought I had event handlers figured out. After hours of searching for a solution, I'm stuck. I'm trying to create a carousel, and while it mostly works, when I attempt to pass an event handler and two variables from one fu ...

Is there a feature in VS Code that can automatically update import paths for JavaScript and TypeScript files when they are renamed or

Are there any extensions available for vscode that can automatically update file paths? For example, if I have the following import statement: import './someDir/somelib' and I rename or move the file somelib, will it update the file path in all ...

Tips for preventing Razor from interpreting special characters as HTML code

I'm encountering an issue with special characters displaying as HTML codes on the page I'm working on. The content is retrieved from a database and shown in readonly input boxes. For example, & is displayed as &. How can I ensure that the ...

JavaScript code to convert a query into an array

Is there a way to search through a JavaScript array to find all names that start with the letter A? If so, how can I display all of the information associated with those names? Name":"Albert","age":"14" Name":"Alison","age":"14" Here is my JSON array: ...

What is the best method for extracting or filtering data from HTML using PHP?

Every day, I receive an email containing an HTML document with statistics from the previous day. The HTML format is difficult for all users to read, so I'm looking to automatically extract information from this table using a PHP script. Below, you&apo ...

What is the process for importing a class (.js file) into a .vue file?

I am facing an issue with my Vue application. I have created a class named `Authenticator` in the file `Authenticator.js`, and now I need to utilize its functions in my `Login.vue` file. Could someone guide me on how to properly export the `Authenticator` ...

I am having trouble retrieving the array value from the response sent by my server

After receiving a dictionary from my server, when I try to access the values using the following code: {"filters":{ "Facture": [ "Магма (Тычок)", "Тонкий кирпич", "Гладк ...

Javascript malfunctioning - exhausted all troubleshooting options

My JavaScript code consists of a single line, but I keep encountering the "getElementById null" error. document.getElementById("menu-background").style.left = "0"; HTML: <html> <head> <title></title> <link rel="style ...

Is there a way to create a flexbox that combines a centered fixed child with a fixed child at the bottom?

I'm trying to create a layout using flexbox that looks like this: | | | | | CENTER FIXED ELEMENT | | | | BOTTOM FIXED ELEMENT | Here is the flexbox CSS I've attempted: .wrapper{ ...

How can server convert the data from Websocket 8.5, which sends `<Buffer>`, into JSON format?

Exploring websocket connections, I am looking to send a JSON object from the client to the server: const WebSocket = require('ws'); const wss = new WebSocket.Server({port: 8082}); wss.on("connection", (ws) => { console.log('s ...

Incorporating new elements onto the page without causing the existing elements to re-render

My challenge involves working with a large array of objects, where each object corresponds to one element. To display these elements on the page, I utilize the map() function, but currently only the first 5 elements are being rendered initially. In order t ...

Tips for Removing Copyright on Charts

Check this out : https://jsfiddle.net/oscar11/4qdan7k7/5/ Is there a way to eliminate the phrase JS chart by amCharts? ...

Leveraging retrieved API data to generate numerous components

Hey there! I'm new to JavaScript and I'm working on creating a todo list with fake ToDos from jsonplaceholder using Fetch. My goal is to fetch five different ToDos and display them in separate list items within my list. However, I'm encounte ...

Please provide the text input for the specified version numbers (1.1, 1.2, 3.0, etc.)

I'm currently working on a form that includes a section for searching by version number: <label class="formLabel">Version</label> <html:text property="valueVersion" styleClass="value" tabindex="11"/> <br/& ...

Tips for maintaining the dropdown selection when new rows or columns are added to a table

I have a task requirement where I must generate a dynamic table using jQuery. I've successfully implemented adding dynamic columns or rows to the table. Feel free to check out the fiddle code here. HTML: <div id='input_div' name='i ...