Create an array of various tags using the ngRepeat directive to iterate through a loop

I'm familiar with both ngRepeat and forEach, but what I really need is a combination of the two. Let me explain:

In my $scope, I have a list of columns. I can display them using:

<th ng-repeat="col in columns">{{ col.label }}</th>

This will render:

<th>Col A</th>
<th>Col B</th>
<th>Col C</th>

Now, in my $scope, there's another variable called mode. When mode is set to 'admin', some admin-related HTML tags are displayed using ng-show. In this case, I would like my columns to be rendered as follows:

<th>config</th>
<th>Col A</th>
<th>config</th>
<th>Col B</th>
<th>config</th>
<th>Col C</th>

Is there a way to use ng-repeat to render both the 'config' and the label column simultaneously? Maybe something like:

<repeat for="col in columns">
  <th ng-show="mode == 'admin'">config</th>
  <th>{{ col.label }}</th>
</repeat>

Alternatively, do I have to create a new list that includes admin columns and regenerate it (using forEach) every time mode changes? What would be the best approach in this scenario?

Answer №1

If you want to iterate a list using AngularJS, consider utilizing the ng-repeat-start and ng-repeat-end directives. Here's an example:

  <div ng-repeat-start="item in items">{{ item.property }}</div>
    Content inside this section
   <div><div ng-repeat-end="">This part of the code will be repeated successfully</div>
  </div>

For more details, check out https://docs.angularjs.org/api/ng/directive/ngRepeat.

Answer №2

It is recommended to utilize a function that retrieves the columns dynamically

$scope.retrieveDynamicColumns = function() {
  if (mode != 'admin') {
    return columns;
  } else {
    var dynamicColumns = new Array(columns.length * 2);
    for (var index=0; index< dynamicColumns.length; index++) {
      dynamicColumns[index] = index % 2 == 0 ? 'config' : columns[parseInt(index/2)];
    }
    return dynamicColumns;
  }
}

template

<th ng-repeat="dynamicColumn in retrieveDynamicColumns()" ng-bind="dynamicColumn"></th>

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

Can you please explain the distinction between these two methods of defining controllers?

When defining controllers, what sets apart these two approaches? angular.module('myApp', ['ui.bootstrap']); function CarouselCtrl($scope) { ... } versus this... var myAppModule = angular.module('myApp', ['ui.bootst ...

Preventing parent requests from being triggered when a child element is clicked in Angular 2

I have a similar code structure as shown below and I am trying to achieve the behavior where clicking on the Child Div does not trigger the Parent Div click event. <div class="parentDiv" (click)="parentDiv()"> <div class="childDiv" (click)="ch ...

Sending a POST request to a Flask server using Stripe and AJAX

I am attempting to implement a function that triggers an ajax request when a stripe form is submitted. However, using the .submit() method doesn't seem to be working as expected. Here is my current code: HTML <form action="/download_data" method= ...

Steps for building an API to connect to our proprietary database using the WSO2 API manager

Currently, I am looking to share my data from my personal postgresql database by creating an API. In this case, I plan on utilizing the WSO2 API manager for the process. I am uncertain if I am proceeding in the correct manner, so any advice on the differe ...

"Track the upload progress of your file with a visual progress

I have written this code for uploading files using Ajax and PHP, and I am looking to incorporate a progress bar to indicate the percentage of the upload. Here is the code snippet: <script> $("form#data").submit(function(){ var formData = new ...

Are the dependencies in an angular module listed in a specific order or randomly arranged?

When organizing dependencies in my apps, I typically arrange them based on the order of their usage. However, is there a recommended best practice for this? And does the sequence of dependencies actually impact anything? ...

Converting a string date format to UTC: A step-by-step guide

In my Typescript code, I am trying to convert a date/time format from string to UTC format but currently facing an issue with it. The desired output is as follows: 2018/10/27+16:00 => 20181027T01000Z import * as moment from 'moment' dates=$ ...

How to enable real-time file changes detection in sails for development

I recently embarked on a new project using Sails (built on Express and Node.js). Currently, I am initiating my server with the command: sails lift However, whenever I make changes to the codebase, I need to manually restart the server. Is there a way to ...

A guide to populating a table with JSON data that includes empty cells in AngularJS

I'm dealing with JSON data that includes employee names and salaries over multiple days (1-5). My goal is to display this information in an HTML table using AngularJS, mimicking the layout of the required table below. JSON Data: [{ name: "Jo ...

Retrieve the initial two HTML elements from a Markdown file that has been parsed using NodeJS

Let's say there is a Markdown file being parsed dynamically to generate something like the following output: <h1>hello</h1><p>sometext</p><img src="image.jpg"/><ul><li>one</li>two</li></ul> ...

What is the best way to initiate a page refresh from a separate component in ReactJS?

As a newcomer to React, I am facing an issue in my CRUD application. I have a Main component and in the List Component, I need to fetch data from the server using an API call. The problem arises when I submit a new item in the Create component - I have to ...

JavaScript regular expression for detecting valid characters without repeating a specific character

let rx = /(\/MxML\/[a-z0-9\[\]@/]*)/gi; let s = 'If (/MxML/trades[1]/value== 1 then /MxML/trades[type=2]/value must be /MxML/stream/pre/reference@href'; let m; let res = []; while ((m = rx.exec(s))) { res.push(m[1]); ...

Node.js: Verifying the user's previous login status using Passport

My current express router for users handles user logins using a token system: var express = require('express'); var router = express.Router(); var passport = require('passport'); var User = require('../models/user'); var Veri ...

What is the solution to having a div move along with window resizing without displacing adjacent divs?

After much effort, I still can't seem to get this working correctly. I've been playing around with a section named "RightExtra" and a div inside it called "RightExtraContent". My goal is to allow these two divs to move freely when the window is ...

Moment.js generated an error due to an unhandled promise rejection warning

I'm trying to determine if my current timestamp is equal or greater than a certain value, but I keep encountering errors. Here's my code with the error: {...} exports.validaforgotpass = async (req, res) => { {...} const results = aw ...

Guide to generating a new element and displaying updated data whenever it is retrieved in a React application

I'm completely new to React and I'm struggling with rendering and listing data fetched from Firebase on my HTML page. I attempted the following approach: const Music = ({ match }) => { const [titles, setTitles] = useState([]); // Change ...

Encountering a malfunction while executing an npm command specified in the package.json file

Currently, I am following a tutorial on Node, React, and Express on Udemy. In the tutorial, when I execute the command npm run data:import I encounter the following error: undefined npm ERR! code ELIFECYCLE npm ERR! errno 1 ...

Update array of hotel room reservations using Mongoose

I am currently developing a hotel room reservation system and have defined the attributes in the Room model as follows: rId: String, allocation: [{ date: Number, // 210403 == 2021-04-03 slots: [{ type: mongoo ...

Convert your Airbnb short link into the full link

I am currently developing an application that utilizes Airbnb links as part of its input. So far, I have identified two types of links: Long form, for example: . These are commonly used on desktop. Short form, such as: . These shorter links are often shar ...

Update the page when the React route changes

I am facing an issue with a function in a component that is supposed to load certain variables when the page is fully loaded. Interestingly, it works perfectly fine when manually reloading the page. However, if I use a NavLink to navigate to the page, the ...