What is the best way to showcase the contents of an array in Angular using two separate divs?


I recently came across a scenario where I have an array of strings:

a= ['apple', 'rice','pasta','orange']

There is a button to randomly add items to this array and then save it in the database. For example:

a.push('carrot');
a.save();

I want to display this array in two separate divs on the DOM, with fruits like apple and orange on the left side and non-fruits like rice and pasta on the right side. The split doesn't need to be dynamic. Should I use filters or split the array into two variables and merge them back together later?

My current (messy) solution involves:

var a = getFromDb;
$scope.b = _.filter(a,isFruit);
$scope.c = _.filter(a,isNotFruit);

Fruits : <div ng-repeat=fruit in b> {{fruit}}</div>
Others : <div ng-repeat=notFruit in c> {{notFruit}}</div>

$scope.save = function() {
  var a = $scope.b + $scope.c;
  saveToDb(a);
}

However, I find this method quite ugly and would appreciate if someone could suggest a more elegant solution.

Answer №1

If you specify within scope (or with controller-as):

$scope.b = ['banana', 'bread', 'potato', 'grape']

After that, in the template, you can easily divide b into two sections and use them independently:

<div class="left">
  <span ng-repeat="item in b.slice(0, 2)">{{ item }}</span>
</div>

<div class="right">
  <span ng-repeat="item in b.slice(2)">{{ item }}</span>
</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

Instructions on how to modify a document's content by its unique identifier using Firebase Modular SDK (V9)

I am trying to figure out how to update an existing document for the same user ID in V9 Firebase whenever they log in, rather than creating a new one each time. Any suggestions on how to achieve this? Current Code setDoc( query(collectionRef), // ...

guide for interpreting a complex json structure

I'm attempting to extract data from a JSON file that has multiple layers, like the example below. - "petOwner": { "name":"John", "age":31, "pets":[ { "animal":"dog", "name":"Fido" }, ...

Learn how to execute a method with a dynamic variable in JavaScript

I am currently facing an issue with some code in asp.net core 3.1. I need to pass a variable to the method GetClientCaseType(). An error is thrown when using @Model.GetClientCaseType[myInt], where myInt works fine when set to a specific number, but throws ...

Exploring the world with an interactive map in R, incorporating Shiny and leaflet

I'm currently attempting to integrate a Google layer as the base layer for a Leaflet map in Shiny R. To achieve this, I've been utilizing shinyJs to inject a JavaScript script into my R code and add the map. However, I'm facing an issue wher ...

Using React js to transform objects into arrays for useState

Hey there! I'm currently working on a webshop demo project for my portfolio. I've encountered an issue while trying to fetch data from commerce.js. The data is in the form of objects, which are causing problems when I try to map them. I've a ...

js TouchEvent: When performing a pinch gesture with two fingers and lifting one of them up, how can you determine which finger was lifted?

I am currently working on a challenging touching gesture and have encountered the following issue: let cachedStartTouches: TouchList; let cachedMoveTouches: TouchList; function onStart(ev: TouchEvent) { // length equals 2 when two fingers pinch start ...

Bring in SASS variables to enhance Material UI theme in NextJS

Within my project, I currently have the following two files: materialTheme.ts import { createMuiTheme, Theme } from "@material-ui/core/styles"; const theme: Theme = createMuiTheme({ palette: { primary: { main: "#209dd2", contras ...

Tips for keeping a Youtube video playing even after the page is refreshed

Is it possible to save the current position of a Youtube video and have it resume from that point when the page is refreshed, instead of starting from the beginning? I am considering using cookies to store the last position or utilizing GET. Although my w ...

Having difficulty controlling the DOM within an AngularJS template

My website utilizes AngularJS templates, specifically a Single Page Application (SPA). Within one of the templates, I am utilizing a tab control from the AngularUI library named Ui-Tabset. During the rendering process, this control generates a ul element ...

Troubleshooting a Vue.js issue: How to fix a watch function that stops working after modifying

I have encountered a problem with my code. It seems to be working fine initially after the beforeMount lifecycle hook, but when I try to modify the newDate variable within my methods, it doesn't seem to track the changes. data() { return { ...

After converting my HTML elements to JSX in Next.js, I am experiencing issues with my CSS files not being applied

Hey there, I'm currently working on a website using Next.js. I've converted the HTML elements of a page to JSX elements but for some reason, the CSS of the template isn't showing up. I've double-checked all the paths and even updated th ...

Refine the table by selecting rows that contain a specific value in the href attribute of the <a> tag, and display the parent row when the child row

I've been working on filtering and searching the table below based on the href value. My code successfully filters the displayed columns in the table, but it fails to work when I search for a string within the href attribute. For instance, if I searc ...

When logging `.map()` to the console, it gives me a rough idea of what I want. However, adding the same line of code via innerHTML only displays

After browsing Stack Overflow for some time, I finally created an account and am now asking my first question. I recently began working with APIs to enhance my web development skills. I started by creating an anime information app that I enjoyed, and then ...

Unable to resolve the issue within Angular UI modal

Currently, I am facing an issue with displaying a modal using Angular Bootstrap UI. The modal is supposed to resolve items in the controller, but I am struggling to access those resolved items in the modal controller. $scope.showItemsInBill = function(bill ...

javascriptcode to execute before loading google maps

I am facing an issue with displaying markers on Google Maps. The problem arises when the array with latitude and longitude values is constructed through an Ajax request. Due to the map being loaded before the initialization of the array, I am unable to see ...

Is there a way to invoke a function once grecaptcha.execute() has completed running, but in response to a particular event?

Presently, the JavaScript function grecaptcha.execute is triggered on page load, as shown in the first example below. This means that the reCAPTCHA challenge occurs as soon as the page loads. A more ideal scenario would be to trigger it when the form submi ...

Incorporating session management in Express.js v4 and Socket.io v1

Is there a way to efficiently store and access session data in express.js and use it within socket.io events? I'm currently building a web application with express.js v4, socket.io v1, and utilizing the basic express-session middleware. I've de ...

Checking if the Cursor is Currently Positioned on a Chart Element in Word Addin/OfficeJS

I am looking for a way to determine if the document cursor is currently positioned inside of a Chart element using the Microsoft Word API. My current application can successfully insert text, but when I attempt to insert text into the Chart title, it ends ...

Currently, I am utilizing a Google script to import my emails into a spreadsheet. I am seeking help in identifying and fixing a duplication issue that

For the past few weeks, I have been running a script to gather task data for my company. The script has been running smoothly since 09/03/2023, but recently it started duplicating entries and causing confusion in identifying which tasks are necessary and w ...

Exploring Javascript parameters with the power of jquery

Is it possible to pass a parameter from PHP into a JavaScript function within HTML? I am currently facing an issue where my code crashes when it reaches a certain condition. This is the code snippet causing the problem: $str="<input type='submit&a ...