"Trouble with Angular JS foreach loop: only the final item in the array

Struggling to loop through each item object in a JSON data set and evaluate its value using angular.forEach(). However, only the last item is being returned, making it impossible to perform any meaningful evaluation. Oddly enough, when using console.log(), each item is shown individually.

Any suggestions on how to properly retrieve and evaluate each item?

If you have a more efficient solution, I would appreciate the guidance.

Here's the JavaScript code (AngularJS):

angular.module('bLiApp')
  .controller('AddDataCtrl', ['$scope', 'DataService', function ($scope, DataService) {

    DataService.getItems().success(function(data) {

      $scope.items = data.category.items;

      angular.forEach($scope.items, function(item) {

        // Struggling with returning data here...
        if (item.amount < 600) {
          $scope.amountchecker = 'low';
        } else if (item.amount >= 600 && item.amount <= 650) {
          $scope.amountchecker = 'average';
        } else if (item.amount > 650) {
          $scope.amountchecker = 'too high';
        }

      });
    });
  }]);

And here is the HTML code (AngularJS):

<div class="add-data" ng-controller="AddDataCtrl">
  <div class="data-box clearfix" ng-repeat="item in items">
    <article class="item">
      <p>{{amountchecker}}</p>
      <p><span class="month">{{ item.month.substring(0, 3) }}</span></p>
      <p class="cost">{{item.cost | currency:"&pound;"}}</p>
    </article>
  </div>
</div>

Your assistance is greatly appreciated.

Answer №1

If you want to achieve the same result without using a forEach loop, here's one way to do it:

<div class="add-data" ng-controller="AddDataCtrl">

 <div class="data-box clearfix" ng-repeat="item in items">
    <article class="item">
      <p>
         <span ng-if="item.amount < 600">Low</span>
         <span ng-if="item.amount >= 600 && <= 650">Average</span>
         <span ng-if="item.amount > 650">Too high</span>
      </p>
      <p><span class="month">{{ item.month.substring(0, 3) }}</span></p>
      <p class="cost">{{item.cost | currency:"&pound;"}}</p>
    </article>
  </div>
</div>

This code snippet will display the amount based on its value range. If you need to change the data in the model itself, you can do this directly in the controller like so:

  angular.forEach($scope.items, function(item) {
    item.amountChecker; // create a new property for each item
    // set the value for each item
    if (item.amount < 600) {
      item.amountChecker = 'low';
    } else if (item.amount >= 600 && item.amount <= 650) {
      item.amountChecker = 'average';
    } else if (item.amount > 650) {
      item.amountChecker = 'too high';
    }

  });

This will add a new property called amountChecker to each item in $scope.items. You can then display this value in your ng-repeat by accessing item.amountChecker.

Note: Another user mentioned a shorter solution in the comments section :)

Answer №2

It seems like in each iteration of the loop over $scope.items, you are constantly updating $scope.amountchecker. For example, if $scope.items had items with amounts of 500 and 650, the final value of $scope.amountchecker would be 'average' because it takes on the amount of the last item encountered.

The solution will vary depending on whether you want $scope.amountchecker to reflect all items or just one specific item. If you prefer the latter option, you should update your code like this:

$scope.amountchecker = 'low';

to

item.amountchecker = 'low';

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

Using JavaScript to generate JSON data in a plain text format rather than using HTML

I have a snippet of code that retrieves the user's location every 5 seconds. <div id="geo" onLoad=""></div> <script> function getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPo ...

Are you struggling with NodeJS asynchronous callback not achieving success?

Currently, I am working on developing a scraper that utilizes the async.map feature to iterate through an array, perform certain logic, and then map them to different values. async.map($('.listing tr').toArray(), GetLink, function(err, results) ...

AngularJS - Strange bug encountered when transferring and removing JSON data from cache within a loop structure

The loop is exhibiting odd behavior where the alerts are triggering out of sequence and the JSON data is all being sent simultaneously. I can't figure out why this is happening. I've been grappling with this issue for a while now and any assistan ...

How to target the last child in Flexbox using CSS order property

Is there a way to correctly detect the last child after rearranging divs using flex order? Even though I have set the order in the CSS, it is still recognizing the last child based on the DOM tree. Since the items are dynamic, we can't rely on nth-chi ...

Issue with AngularJs Autocomplete: this.source is not being recognized as a function

Below is the HTML code snippet for an autocomplete textbox feature: <body ng-controller="HomeController" ng-init="init()"> <div class="col-xs-4 search-bar-position" > <form role="search" > <div c ...

Arrange the menu items in a column layout based on a given condition

Can someone assist me with displaying the menu subitems? I have created a plunker. Take a look at it to understand what I need (open plunker in full screen) https://plnkr.co/edit/IMEJFPfl5kavKvnUYaRy?p=preview In the plunker above, there are two dropdown ...

The Vue.js route is not aligning with its defined path, causing a mismatch

Attempting to develop a Vue SPA app, but encountering an issue with the routes not matching what was defined in the router. Despite all configurations seemingly correct, there is confusion as to why this discrepancy exists. What element might be overlooked ...

The form validation feature in NestJS using Class Validator appears to be malfunctioning

Hey everyone, I've been working on validating incoming form data using the class validator package and DTO. Here's my DTO: import { IsString, IsPhoneNumber, IsEnum, MinLength } from 'class-validator'; export class CreateAgentDto { @ ...

Having difficulty showcasing API call results in a Vue.js component

I am currently experimenting with Vue.js in an attempt to showcase results from a Wikipedia API call within a component using the v-for directive. However, I seem to be encountering some backend issues that I cannot pinpoint. To access the jsFiddle link, ...

A JavaScript right-click menu that updates a variable when clicked

Within my three-dimensional application created with three.js, I have implemented a functionality where right-clicking on floors (BoxGeometry) triggers a context menu to select from various textures. While this feature works as intended for a single floor, ...

When attempting to submit a record at http://localhost:5173/, a 404 (Not Found) error was

Currently, I am attempting to retrieve username data and timeTaken from a form. My goal is to send this data to my server, create the User object, and store it in MongoDB Atlas. Unfortunately, I am encountering a 404 error that I am struggling to resolve. ...

Displaying and hiding the top menu when the div is scrolled

I have developed a script that is designed to display the menu in a shaking motion and hide it as you scroll down. It functions properly when scrolling within the body of the webpage, but I am facing issues when attempting to do so with a div that has an o ...

Using a Python list as an argument in a JavaScript function

How can I pass a python list as an argument to a JS function? Every time I attempt it, I encounter the error message "unterminated string literal". I'm baffled as to what's causing this issue. Here is my python code (.py file): request.filter+= ...

The `finally` function in promises is failing to execute properly

Currently working with Typescript and I've included import 'promise.prototype.finally' at the beginning of my index.js file (in fact, I've added it in multiple places). Whenever I try to use a promise, I encounter the error message say ...

Invoke an Angular service from a separate JavaScript file

I have a few javascript and html files: User.js, index.html, Door.js I am looking to utilize a function in the User.js file. Link to my user.js file Link to my door.js file I am trying to call the getUserInfo function from User.Js within the Door.j ...

Executing a command upon the pressing of the enter key within a text input field

Here is my input field: <input type="text" id="word" /> I am looking for a JavaScript function that will be triggered when the user hits enter in this text box. I searched for an answer but couldn't find one that fits my spe ...

I am experiencing issues with my $ajax request

After running the code snippet below: websiteUrl= "http://192.168.2.171/LoginAuthentication"; $.ajax({ url: 'websiteUrl', type: 'GET', success: function(response) { var title = $(response.responseText).find('a. ...

What is the best way to gather Data URI content through dropzone.js?

I am currently utilizing Dropzone for its thumbnail generation feature and user interface. However, I am only interested in using the thumbnail generation ability and UI and would prefer to collect all the data URIs myself and send them to the server via a ...

Reading and decoding JSON data using AJAX

Upon viewing the console, I receive the JSON data in the following format: [Object] 0: Object address: "soham" region: "soham" relevanceScore: "4" startDate: "2015-05-10" subscriptionType: "1" verificationStatus: "1" __pro ...

What is the correct way to encode an HTML string in JavaScript?

I have identified a XSS Scripting vulnerability in my code and I want to prevent it. To do so, I am utilizing a Jquery Encoder for protection against XSS Scripting attacks. Below is the JavaScript code snippet: function test(response) { $('#test ...