changing the items in ng-repeat based on their position in the index

I am using ng-repeat to populate my web page with data fetched from a Rails API.

Within my array, I have 2 objects each with different prices.

The goal is to present the user with a price per hour, but the division factor should vary based on the index of the item in the array. Currently, the code calculates the total price for each item, but I want to divide them differently.

This is the current code:

Javascript/Angular

apiCall(function (data) {
    for(var i=0; i<data.length;i++){
    controller.holder.push({
    id: data[i].id,
    price: data[i].price  
  });
}

controller.holder = [
  {
    id: 1,
    price: 100
},{
   id: 1,
   price: 500
}]

HTML

 <div ng-repeat="pack in Test.holder" class="col-sm-6">
      <p>{{pack.hours}}  - {{pack.price | currency }}</p> 
      <button translate>Go</button> 
</div>  

Desired output should be something like this (refer to comments in the code):

<div ng-repeat="pack in Test.holder" class="col-sm-6">
//if pack index in holder is 0 divide the item by 5
//if pack index in holder is 1 divide the item by 10 
          <p>{{pack.hours}}  - {{pack.price | currency }}</p> 
          <button translate>Go</button> 
</div>  

Is there a way to achieve this using $index? Extensive research has not yielded a clear solution.

Your assistance would be highly appreciated. Please feel free to ask for further details if needed.

Answer №1

If you're looking to split the cost by 5 or 10:

<div ng-repeat="package in Test.collection" class="col-sm-6">
   <p ng-if="$index == 0">{{package.duration}}  - {{package.cost / 5 | currency }}</p> 
   <p ng-if="$index == 1">{{package.duration}}  - {{package.cost / 10 | currency }}</p>
   <button translate>Proceed</button> 
</div> 

Answer №2

For optimal results, I recommend utilizing both the $index function and ng-if directive in tandem.

When the index is less than 5, execute one action; otherwise, proceed with another.

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

AngularJS - Array binding issue not updating in directive

I am currently developing a directive that has the ability to display a series of controls. Each individual control is implemented as a directive named fsFilter. In the controller managing the parent element, I establish a binding between the filters arra ...

How many records are there in Mongo DB?

How can I query mongoDB to count documents with a specific date? For example, let's say I have the following documents: [ { fullDate: '2020/02/01', someData: 'someData', }, { fullDate: '2020/03/01', someData: 'someD ...

Retrieving the output value from a callback function in Sqlite3

In my current project, I am using Sqlite3 with an Express backend along with a React frontend. My goal is to verify if a user with a specific email exists in the database. While working on the function provided below, which is still a work in progress, I e ...

What methods can be used to maintain the selected date when the month or year is changed in the react-datepicker component of reactjs?

At the moment, I am using the Month selector and Year selector for Date of Birth in the react-datepicker component within a guest details form. The current functionality is such that the selected date is highlighted on the calendar, which works fine. How ...

When using findOneAndUpdate, it allows for making incremental updates

My current challenge involves updating a database document based on user input, determining its existence, and creating it if necessary. The scenario involves users retrieving the stock price of a company and being able to like it once. async func ...

Is it possible for two buttons to have the same 'click' function?

I am encountering an issue with duplicated buttons in my code. I have two buttons, one named Update and the other named View. Initially, both buttons work perfectly fine. However, when I duplicate these buttons, only the View button retains its functionali ...

Processing Incoming HTTP Requests in AngularJS Server Backend

Recently diving into AngularJS for my web development projects has been a game-changer. However, being a newbie in the realm of web programming, I've been struggling to find a concise answer to my current query. The burning question on my mind pertain ...

JavaScript and the importance of using commas in arrays

I am developing a system that displays text in a textarea when a checkbox is checked and removes the text when the checkbox is unchecked. The functionality is mostly working as intended, but I am facing an issue where commas remain in the textarea after un ...

The AJAX request is now being "canceled" since the website is up and running

After successfully running AJAX requests on my new version, which was in a sub directory of my site (www.staging.easyuniv.com), I moved the site to the main directory to make it live (www.easyzag.com). Although everything seems to be functioning properly, ...

Checking URL validity with regular expressions in Vue JS

Currently, I am attempting to validate URL strings utilizing a regular expression. The following regex is what I am using for this purpose: var regex = /^(http|https):\/\/+[\www\d]+\.[\w]+(\/[\w\d]+)?/ With thi ...

Traverse is not defined and performance is slowing down with the THREE.js Clock, even though it technically functions

Everything seems to be functioning as intended – moving through the scene, updating the meshes. However, not all of my meshes are showing up on the list, even though they are being rendered (quite bizarre). Additionally, I keep getting error messages cla ...

The combination of jQuery event handling and accessing undeclared event objects

While debugging someone else's code, I encountered a puzzling situation. The snippet of code provided below illustrates the problem. It seems to me that event should be undefined upon entering the event handler. This is indeed the case in Firefox, bu ...

Leveraging jQuery selectors to manipulate data received from an Ajax response

I am encountering an issue with an Ajax call and response. Previously, I had a block of regular javascript code that successfully transformed my select element into a select2 widget. However, when I attempt to convert the select element into a select2 usi ...

What is the best approach for transforming repetitive React code patterns into a reusable component or object?

Take a quick look at this section without overanalyzing it, and focus on the similarities among each group. // LOADING VENDORS const [loadingVendors, setLoadingVendors] = useState<boolean>(true); const vendorsErrorTimeout = useRef<NodeJS.Timeout|n ...

determine which specific button triggered the validation process

Is there a way to identify which button was clicked using JavaScript? I have validation in place, but I want it to only validate when a specific button is clicked and not when other controls are interacted with. PLEASE NOTE THAT I HAVE 3 TEXTBOXES SIMILAR ...

Unable to retrieve the status for the specified ID through the use of AJAX

When I click the button in my app, I want to see the order status. However, currently all statuses are being displayed in the first order row. PHP: <?php $query = mysqli_query($conn, "SELECT o.orderid,o.product,o.ddate,o.pdate,k.kalibariname,o.sta ...

What are some strategies for ensuring accurate data retrieval from the process.env file?

I am facing an issue where I need to retrieve data from a .env.local file, but instead of fetching the data from the file in the current folder, it is pulling the information from another project that I previously created. How can I instruct node.js to ide ...

PrototypeJS version of Django Debug Toolbar

My admiration for Django Debug Toolbar is immense. However, a challenge arose when I realized that it heavily relies on the Jquery framework for its UI enhancements, while my application is built on Prototypejs. This has led to confusion in the browser r ...

Error: Unable to access the 'CustomerId' property because it is undefined

Recently, I made some updates to my website. As part of the upgrade process, I switched to AngularJS v1.7.6 and JQuery v1.12.1. However, after making these changes, I encountered an error in my console log. TypeError: Cannot read property 'CustomerId ...

Whenever I navigate to localhost:3000 while using Next JS, it redirects me to 'http://localhost:3000/public/index' and displays a 404 error

In my pages folder, I don't have a public folder. Instead, I have the index.js file directly inside the pages folder. However, when I start the server at localhost:3000/, it automatically redirects to http://localhost:3000/public/index and displays a ...