Transforming a javascript function into an AngularJS function

I have been attempting to convert the JavaScript function into AngularJS, but I keep encountering errors due to my limited experience with AngularJS.

var array = [5, 5, 7, 9, 9, 9];
var max = array[0],
    total = 0;
array.forEach((a) => {
  if (a == max) {
    total += max;
  } else if (a > max) {
    max = total = a;
  }
});
console.log("total:", total);

The var array[] is now being retrieved from GET data and I have made this adjustment in my AngularJS code.

$scope.List = getAllList;

$scope.deptime =function (){
   $scope.array = $scope.List.Time;
   console.log($scope.array);
   $scope.max = $scope.array[0], $scope.total = 0;
   angular.array.forEach((a)=>{

       if(a==$scope.max){
          $scope.total+=$scope.max;
       }
       else if(a>$scope.max){
          $scope.max = $scope.total = a;
       }

    });
    console.log("total:"+$scope.total);
};
$scope.deptime();

I am currently facing this error:

TypeError: Cannot read property '0' of undefined

Where could I possibly be making a mistake?

EDIT :- My response from the service is being obtained in this section :- $scope.List = getAllList;

Answer №1

If the getAllList service is properly implemented, update your code in this way:

getAllList()
  .then(function(res) {
    $scope.List = res;
    $scope.deptime();
  });

Furthermore, replace instances of angular.array with $scope.array in the deptime function.

$scope.array.forEach((a) => {
  if (a == $scope.max) {
    $scope.total += $scope.max;
  } else if (a > $scope.max) {
    $scope.max = $scope.total = a;
  }
});

Additionally, if you do not require max, total, and array outside of the function, modify your function as follows:

$scope.deptime = function() {
  let array = $scope.List.Time;
  let max = $scope.array[0],
    total = 0;
  $scope.array.forEach((a) => {
    if (a == max) {
      total += max;
    } else if (a > max) {
      max = total = a;
    }
  });
  console.log("total:" + total);
  return total;
};

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

Tips for animating input width as the size value changes during an ajax query transformation

This is my JavaScript code: function updatePriceDisplay() { $.ajax({ url:"query.php?currency=<?=$currencycode;?>" }).done(function(data) { $("value").attr("value", data).attr("size", data.length - 2); }); } updatePriceDi ...

Enhance your angular.js factory using the Chrome Developer Tools

How can I override the downloaded angular.js factory using dev tools? I need to add some client-side log statements but cannot deploy any code. Updating normal Javascript functions in console is easy, but I'm struggling with angular.js factories. ...

What are the steps to turn off the blue hyperlinks on iOS devices?

One example of this issue can be observed in time-formatted text like (00:10 - 10:55) and a time select menu displaying (08:00 AM). I have attempted the following solutions, but none of them have resolved the problem: Mobile Safari/iPhone Mail.app HTML ...

Vue paginated select with dynamic data loading

My API has a endpoint that provides a list of countries. The endpoint accepts the following query parameters: searchQuery // optional search string startFrom // index to start from count // number of options to return For example, a request with searchQu ...

Obtaining data from an ajax request in node.js

My webpage has a feature that triggers an ajax request: $.ajax({ type: 'POST', url: '/usernamecheck', data: {"username":username}, success: function(taken){ ...

Switch the visibility of all local variables in *ngFor from an external loop

Imagine having an *ngFor loop where a local variable is defined like this: <div *ngFor="let item of items"> <p>{{item.name}}</p> <div *ngIf="item.colorVisible">{{item.color}}</div> <button (click)="item.colorVisible ...

Unable to retrieve the properties of a JavaScript object

Currently I am working on a React webApp project and encountering difficulties when trying to access data within a JavaScript Object. Below is the code snippet in question: const user_position = System.prototype.getUserPosition(); console.log({user ...

Error message: The requested resource could not be loaded due to a server error (status code 500) when using

I have been struggling to identify the exact issue with my code, despite referencing previous questions on the topic. function viewcalldetails(obj) { alert("clicked"); var id = $(obj).attr("id"); $(".style-t ...

Challenges with the efficiency of the Material UI Datagrid

I am currently using MUI Datagrid to display my records, but I am experiencing delays with my modal and drawer components. Even after attempting to optimize with useMemo for my columns, I have not been able to achieve satisfactory performance. https://i.st ...

Avoid content duplication when appending content using the append() function

When I try to append content to a page using javascript and jQuery, it works perfectly in Chrome. However, when testing it out in Firefox, the appended content ends up getting duplicated. Here's an example of what I'm talking about: https://i.ss ...

Please ensure to provide a boolean value when using wrapper.setChecked() in Vue Test Utils

Working on a project with Vue, I have implemented some radio inputs: <label> <input v-model="myProperty" v-bind:value="true" name="myProperty" type="radio" > True </label> <label> <inpu ...

Including numerous pins on a map

I am currently working on a project that involves extracting data from PHP records to plot markers on a leaflet map using coordinates. Unfortunately, I encountered an error in the console: Error: Invalid LatLng object: (18.473396, undefined) Here is th ...

Use ng-repeat to dynamically calculate the sum of values in a textbox in AngularJS

Greetings everyone! I am currently utilizing AngularJS and I am attempting to sum the values that are entered in an ng-repeat text box, row by row. However, my current solution sums up all the data instead of doing it row by row. Can anyone offer guidance ...

Disrupting a Program Operation

We are utilizing the gauge Google Chart applet to visually track the failure rates of message transfers on a SOAP interface via AJAX. My goal is to make the page's background flash red and white when the failure rate reaches 50% or higher, and remain ...

What is the best way for an object to recognize if its value matches a key in another object, and then retrieve that value

Is there a way to make an object detect if its value is equal to another object's key and then retrieve it? Let's consider the following object named: AnswerString let AnswerString ={ 0: "B", 1: "x" } and the answers are in different objects, ...

Track the number of views a movie receives on your website by utilizing the capabilities

I am brand new to Google Analytics. I have a collection of movies on my website and I'm curious if there's a way to utilize GA to track how many times each specific movie has been played. Can anyone offer guidance on this? Thank you! ...

steps for populating default configurations in an angularjs application

As someone who is just starting out with AngularJS and MVC, I have a confession to make. In the past, my website development process was quite messy - some might call it "spaghetti code." Now, I'm looking to incorporate some basic settings into my w ...

Guide to inserting a unique directive div after a specific ng-repeat element

I have multiple items being rendered through ng-repeat in my code. Each item utilizes the bootstrap class col-md-3. My goal is to implement a functionality where users can click on an item and view a larger detail panel. However, I want to achieve this by ...

C++ equivalent to Python's list append function

Currently diving into the world of C++ after spending time in Python. I'm curious if there is a method to add elements to an array in C++? myArray = {}; for (int i = 0; i < 10; ++i) { myArray.push_back(i); } Is there a similar approach avail ...

Caution: The React Hook useEffect is missing a dependency: 'postImage'. Make sure to include it or remove the dependency array before running npm run build

Every time I run the npm run build command in my project, a warning message is displayed stating that Warning: React Hook useEffect has a missing dependency: 'postImage'. Either include it or remove the dependency array. react-hooks/exhaustive- ...