Using data-ng-repeat with various elements in Angular

Within the Angular controller, there is a variable that contains the following:

$scope.items = [
  { title: 'x', type: 'x'},
  { title: 'y', type: 'y'}
];

Currently, there are only 2 items in the array, but there will be more added in the future. To display this array in HTML, I plan on using the ng-repeat Angular directive. However, I am facing a challenge: I need to render a different HTML tag based on the type of each item. For items with type 'x', I need to render <x-tag>, and for items with type 'y', I need to render <y-tag>. How can I achieve this? Any help is greatly appreciated!

Answer №1

Include a :filter within the ng-repeat directive:

var app = angular.module('myapp', []);
app.controller('myctrl', function($scope) {
  $scope.items = [{
    title: 'x',
    type: 'x'
  }, {
    title: 'y',
    type: 'y'
  }, , {
    title: 'another x',
    type: 'x'
  }];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myapp" ng-controller="myctrl">
  <div>Display only items with type 'x':</div>
  <ul>
    <li ng-repeat="item in items | filter: {type: 'x'} ">{{item.title}}</li>
  </ul>

</div>

Answer №2

Combine ng-repeat and ng-switch in your AngularJS app:

angular.module('myApp', [])
.controller('myCtrl', function($scope) {
  $scope.items = [
    { title: "TestX", type: "x" },
    { title: "TestY", type: "y" }
  ];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.js"></script>

<div ng-app="myApp" ng-controller="myCtrl">
  <div ng-repeat="item in items">
    {{ item.title }}
    <div ng-switch="item.type">
      <div ng-switch-when="x">
        HTML for type x
      </div>
      <div ng-switch-when="y">
        HTML for type y
      </div>
    </div>
  </div>
</div>

Answer №3

In addition to ng-hide, you can hide an element if a certain condition is met.

<div ng-repeat="item in items" >
        <div ng-hide="item.type == 'y'">
        {{ item.type }}
        </div>
        <div ng-hide="item.type == 'x'">
        {{ item.type }}
        </div>
</div>

Answer №4

When you need to display items of type x exclusively, you can utilize the 'filter' attribute within the ng-repeat directive or use ng-if.

<div ng-repeat="item in items"> 
    <div ng-if="item.type==='x'">
       <p>Showing items of type x</p>
    </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

What is the best approach to assigning a default value to each cascading dropdown using Angular?

I've successfully implemented the dropdown functionality below. Now, I just need help setting default values for each level in the hierarchy. While I know how to do this for the top-level, I'm unsure of how to set defaults for subsequent levels. ...

The dropdown menu is malfunctioning when accessed within the mobile view of a jQuery

Take a look at this code snippet on Fiddle: https://jsfiddle.net/rizwanali98601/ngofhc24/12/. The table below contains a dropdown inside a jQuery Datatable. When the button is clicked, an option is supposed to be added to the dropdown. However, in mobile ...

Conceal rows in the table until the search (filterBy) is completed

Currently, I am utilizing Vue.js version 1.x and plan to update soon. My requirement is to have a table of rows containing some data. To filter the table rows using filterBy, I am using a Vue.js component. However, I want the table rows to remain hidden un ...

What is the reason for React.Component being implemented as a function rather than an ES6 class?

After delving into the codebase of React, I made an interesting discovery. When you define a class like class App extends React.Component, you are essentially extending an object that is generated by the following function: function Component (props, cont ...

Unique syntax using markdown-react

I want to customize the syntax highlighting in react-markdown. Specifically, I would like to change the color of text inside {{ }} to blue while still maintaining the correct formatting for other elements, such as ## Header {{ }} import React from " ...

"Encountered an issue while attempting to access properties that are undefined, specifically with the operation 'includes

I'm encountering a specific error message TypeError: Cannot read properties of undefined (reading 'includes') while running my test in React. The issue seems to be related to a line in my code where the test fails to progress, but commenting ...

Express.js throwing an unexpected 404 error

I'm really struggling to understand why Node (express) only renders the index page and returns a 404 error for other pages, like "comproAffitto" in this example. In my app.js file: var index = require('./routes/index'); var comproAffitto= ...

What is the process for defining custom properties for RequestHandler in Express.js middleware functions?

In my express application, I have implemented an error handling middleware that handles errors as follows: export const errorMiddleware = (app: Application): void => { // If the route is not correct app.use(((req, res, next): void => { const ...

Link the Sass variable to Vue props

When working on creating reusable components in Vue.js, I often utilize Sass variables for maintaining consistency in colors, sizes, and other styles. However, I recently encountered an issue with passing Sass variables using props in Vue.js. If I directly ...

Tips for configuring <link> in NextJs to only activate on a single click

I am currently utilizing the Flickity-React-Component to create a swappable Carousel and I have included NextJs <Link> in its children. However, the issue arises when I click and swap the carousel - after releasing the mouse click, it automatically ...

Exchange of Fusion Chart

Attempting to perform a fusion chart swap with asp has proven to be challenging. The alternative approach involves rendering the fusion chart first and then using onmousedown to replace the chart with an image. However, this method is also encountering i ...

Troubleshooting React on an Apache Server: A Comprehensive Guide

An interactive React application utilizing React Router has been successfully deployed on an Apache server. After making modifications to the .htaccess file, most of the routes function correctly as intended. Some specific routes within the app rely on us ...

A step-by-step guide on how to fill a Vuetify select box with data retrieved from

I'm currently working on populating a select box in Vuetify by retrieving data through an ajax call. I'm struggling to figure out how to populate the select box with this data. The ajax call is successful and I receive an array of objects which I ...

Adding a JSON object or model to your whitestorm.js environment: Step-by-step guide

I have a challenge with loading the object from my json file. const loader = new THREE.ObjectLoader(); loader.load("blue-car.json", function ( car ) { car.position.set(2, 0, 0); car.addTo(world); } ); However, I encountered an error. Here is the err ...

Dynamic Website (Link Relationships / Responsive Design / Content Rendering with CSS and HTML)

Hello everyone! My name is Mauro Cordeiro, and I come from Brazil. I am just diving into the world of coding and have been following various tutorials. Stack Overflow has been an invaluable resource for me in my learning journey! Aside from coding, I am a ...

When selecting a dropdown in Angular 5, the aria-expanded attribute remains unchanged and the 'show' class is not applied. This behavior is specific to Bootstrap dropdowns

Having an issue with the bootstrap dropdown in my Angular project. When I click on it, the dropdown-menu does not show up. The 'show' class is not being added to the dropdown and the 'aria-expanded="false"' attribute does not change to ...

Check the validity of a watched variable's value and block any assignments that do not meet the specified requirements without triggering the watch function

Check out my jsBin snippet here I am experimenting with watching a variable's value and handling failed validation by returning its previous value without triggering the watch function again. I am considering the following scenario: If validation ...

Understanding how to sum the values of two separate dropdown selections using jQuery

Is it possible to combine and total up two different selections to display on the "Total" button below? I have added calculations to each selection. When a user selects a quantity, it should automatically sum up and display on the "Total" button, but I am ...

Leveraging dynamic visuals for your Twitter metadata image

My Twitter application automatically posts the current title being broadcast on my web radio every 20 minutes. It includes details like the artist, number of listeners, and playlist, but does not display album covers. To work around this limitation, I am ...

Enhance Compatibility: IE11 URL Polyfill

While creating a URL in my angular app using new URL, I have encountered an issue that it works on all browsers except IE11. To resolve this problem, I attempted to add "url-polyfill" to my "package.json" and imported 'url-polyfill' in the polyf ...