Can I maintain the separation of two arrays in Angular and still utilize them in an ng-repeat?

Before we proceed, let's reference this question: Angularjs map array to another array

Presently, I am managing two distinct scopes:

$scope.products = [
  {id: 001, name: "prod 1", ...},
  {id: 002, name: "prod 2", ...},
  {id: 003, name: "prod 3", ...},
  {id: 004, name: "prod 4", ...},
  {id: 005, name: "prod 5", ...}
]

$scope.cart = {
  products: [001,002]
  ...
}

The collection $scope.products contains details about all available products, while $scope.cart.products holds the IDs of items in the cart.

The linked answer demonstrates merging these arrays. Nonetheless, I am keen on maintaining their separation and establishing a mapping between them. Is that feasible? Should I opt for a custom filter within the repeater, or does Angular offer a native solution? Appreciate any guidance

UPDATE

Utilizing a Filter:

filter('mapProducts', function($filter) {
  return function(products, ids) {
    var result;
    result = [];
    $filter('filter')(products, function(p) {
      if (ids.indexOf(p.id) !== -1) {
        return result.push(p);
      }
    });
    return result;
  };
});

Incorporate this in the repeater:

<div ng-repeat="product in products | mapProducts:cart.products">

Answer №1

There isn't much to gain from avoiding the creation of a new array. Utilizing an Angular filter can help "map" the results, offering a cleaner approach compared to handling it in the controller. However, at its core, Angular still generates a new sub-array behind the scenes. Even if you opt for a custom filter, ultimately, a new array is being formed.

angular.module('myApp').
  filter('idNumber', function() {
    return function(products,idNumbers) {
      var newArray= [];
      newArray = products.filter(function(p) {
        return idNumbers.find(function(i) {
          return i == p.id;
        });
      })
      return newArray;
    }
  });

In addition, when using the view version of the filter:

ng-repeat="product in products | myFilter: cart.products"

There may be performance implications depending on the size of your array:

The filter can be applied in the view template with markup like {{ctrl.array | filter:'a'}}, which would conduct a fulltext search for "a". However, integrating a filter in a view template will reevaluate the filter during each digest cycle, potentially resulting in higher costs for larger arrays.

Therefore, it's recommended to apply the filter in the controller:

var newArray = $filter($scope.products, 'myFilter', cart.products)

This approach also involves creating a new array.

Answer №2

In this setup, you can make $scope.cart.products an array consisting of references to objects in the $scope.products array:

$scope.products = [
  {id: 001, name: "prod 1", ...},
  {id: 002, name: "prod 2", ...},
  {id: 003, name: "prod 3", ...},
  {id: 004, name: "prod 4", ...},
  {id: 005, name: "prod 5", ...}
];

$scope.cart = {
  products: []
};

$scope.addProduct = function(product) {
  $scope.cart.products.push(product);
}

This approach essentially links the two arrays via object references:

$scope.addProduct($scope.products[1]);

// This will evaluate to true
$scope.cart.products[0] === $scope.products[1]

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

Is there a way to turn off _moz_resizing on my browser?

I am currently using the nicEdit editor and have successfully integrated my own custom image resizing script. However, I am facing an issue where the default _moz_resizing feature in Firefox is interfering with my custom script. My goal is to have specifi ...

Creating a Dynamic Soundtrack: How to Embed an Audio

Success! I finally figured it out, with a little help from everyone. I've been diving into the world of Audio Playlists in HTML and attempted to follow a tutorial on the topic found here: https://www.youtube.com/watch?v=vtZCMTtP-0Y. However, I encoun ...

If a user enters an incorrect path, the goal is to automatically redirect them to the homepage while displaying the correct URL in AngularJS

When the URL is manually edited, the webpage displays the same content with a different URL structure. For instance, http://www.example.com/# and http://www.example.com/#/abc both show identical content. I would like to implement a redirect for any edite ...

Colorful D3.js heatmap display

Hello, I am currently working on incorporating a color scale into my heat map using the d3.schemeRdYlBu color scheme. However, I am facing challenges in getting it to work properly as it only displays black at the moment. While I have also implemented a ...

updating the count of items in a react virtual list

Popular libraries such as react-virtualized, react-window, and react-virtuoso all include an item count property similar to the one shown in the code snippet below from material-ui. However, this property is typically located within the return statement. ...

Error: The file 'templates.js' cannot be found or accessed by gulp-angular-templatecache. Please check the file path and make sure it

I have set up a basic structure for creating angular templates using Gulp. Here is the code snippet from my gulpfile: var gulp = require("gulp"), templateCache = require('gulp-angular-templatecache'); gulp.task("tc", function() { retur ...

Attempting to perform recursion on two functions simultaneously may result in one of the functions being undefined

There is a page on my site that clients tend to keep open for long periods of time without refreshing, sometimes over 24 hours. Some of the actions on this page require a valid PHP session, so I created a simple set of functions to check this every 10 minu ...

As time passes, the Azure Service Bus Consumer experiences a decline in performance

My issue involves managing different topics with subscriptions, each tied to a consumer. Over time, I've noticed a decline in the number of messages received. Despite trying to utilize maxconcurrentcalls, it seems to only be effective at the start. My ...

How to Use jQuery Slice to Display the Top N Items from a Dropdown Menu

How can I display only the top 10 results from multiple UL lists in my navigation? The code snippet provided below currently works for the first list, but how can I extend this functionality to all of the lists? $(document).ready(function() { var elem ...

The concept of using the `map` method within a

Hi there, I could use some assistance with a tricky issue I'm facing. My current task involves rendering a cart object that includes product names, prices, and quantities. Each product can have its own set of product options stored as an array of ob ...

Taking out a specific value from a cookie collection

I am attempting to eliminate a specific value from a cookie array:- if (!empty($_GET['job_unfav'])) { $value_to_delete = $_GET['job_fav']; // The value to be removed from the cookie array $favouriteIDs = explode(&apo ...

Click on the radio button to delete all selected entries in the option dropdown

After spending the entire day trying to find a solution, I am still struggling with a simple task - how do I clear all selections from a group of select option drop downs at once without removing them? I want the selections to revert back to their default ...

In JavaScript, generate a new column when the text exceeds the height of a div

Is it possible to create a multicolumn layout in HTML that flows from left to right, rather than top to bottom? I am looking to define the height and width of each text column div, so that when the text overflows the box, a new column is automatically ge ...

What could be causing my token to not save after registering a user?

I am currently facing an issue when submitting a registration form. While the user is successfully created, the token is not stored in localStorage, which prevents me from being redirected immediately to the app and forces me to log in again. Here is my R ...

Submitting a JavaScript array to MongoDB using a React application: A guide to success!

As a beginner delving into the world of React and MongoDB, I'm encountering difficulties in establishing communication between the two technologies. Recently, I've been following a detailed tutorial on Medium that focuses on utilizing the Plaid A ...

Tips for resolving the java.lang.NumberFormatException caused by an empty string in Java

Whenever I try to run the code below, it keeps returning a java.lang.NumberFormatException: empty String error but I am unable to pinpoint the exact reason behind it. import java.util.ArrayList; import java.util.List; import java.util.Scanner; public clas ...

The Axios GET request was not functioning properly after attempting to use Axios stream.on("data")

I am working with a backend API that has an endpoint named /subscribe, which gives back a continuous stream of data. Along with this, I have a node process, and I am utilizing axios to send a request to my backend API with a response type of "stream& ...

Modifying the background hue of a text box within an external stylesheet

I'm currently facing an issue where I need to change the color of a textarea when a radio button is clicked. There are 4 radio buttons, so the textarea should change color 4 times for each button. I am working in reactjs and despite researching the pr ...

Restrict the character count in the input field according to its width

Is there a way to restrict the number of characters in an input field based on its width? I have a dynamic input field with varying widths and I would like users to be able to type without their text extending outside of the input boundary. Using maxLeng ...

`Troubleshooting Firebase Cloud Functions and Cloud Firestore integration`

I previously used the following Firebase Database code in a project: const getDeviceUser = admin.database().ref(`/users/${notification.to}/`).once('value'); Now, I am attempting to convert it for Firestore. My goal is to retrieve my users' ...