The ng-repeat function I have been using seems to be repeating excessively, far beyond the actual length of the array

When looping through an array of 5 elements, a function is being called inside the ng-repeat.

$scope.myArray=[1,2,3,4,5]
var i=0;
$scope.diffHours= function(){
    i++;
    console.log(i)
    return "string";
}

<div ng-repeat="item in myArray">
  {{diffHours()}} 
</div>  

Surprisingly, the function is being called 40 times in total instead of just 5 times corresponding to the array elements.

https://i.sstatic.net/G8HHj.png

This is the code snippet:

<script id="view.html" type="text/ng-template">
<ion-view view-title="Second page">
  <ion-content class="padding">
      <div ng-repeat="item in myArray">
         {{diffHours()}} 

      </div>            
  </ion-content>
</ion-view>

nameApp.controller('ViewCtrl', function($scope, $stateParams, $ionicHistory) 
{
  $scope.myArray=[1,2,3,4,5]
  var i=0;
  $scope.diffHours= function(){
      i++;
      console.log(i)
      return "string";
  }
});

This scenario showcases a simplified version of my issue, though I have more complex operations and libraries in my actual project that are not displayed here.

Any insights on what could be causing this?

Updated link below:

https://plnkr.co/edit/e8Jfu000vbvnGS9QfnWQ?p=preview

Answer №1

Angular's digest cycle is triggered by changes in $scope, causing a reevaluation of all elements. When using a function within $scope, it will be called again to retrieve updated values, potentially leading to performance issues. To avoid this, refrain from adding new keys to $scope and instead create variables with var. Remember to still bind the $scope variable to HTML.

nameApp.controller('ViewCtrl', function($scope, $stateParams, $ionicHistory) {
  var myArray = [1, 2, 3, 4, 5],
    diffArray = [];
    var i = 0;
    var diffHours = function() {
      i++;
      console.log(i)
      return "string";
    }

  myArray.forEach(function(item) {
    diffArray.push(diffHours(item))
  })
  $scope.diffArray = angular.copy(diffArray);

});

You can also use 'track by' to assign unique values. I have used index in this example, but adjust based on your data.

 <div ng-repeat="item in diffArray track by $index">
         {{item}} 

      </div>    

I hope this provides clarity for your question. Best of luck!

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

The Bootstrap carousel spiraled into disarray

I am facing an issue with the basic bootstrap carousel. My goal is to make the slides move every four seconds. The current setup of the carousel code is as follows: $(document).ready(function() { fixCarousel(); }); function fixCarousel() { $('.c ...

Cease the progress of a Sequelize promise within an Express.js application

Exploring the realm of promises is a new adventure for me, and I'm still trying to grasp their full potential in certain situations. It's refreshing to see Sequelize now supporting promises, as it greatly enhances the readability of my code. One ...

Having trouble getting the Pokemon modal to show both the type and image?

HTML: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>My First JS App</title> <lin ...

Utilizing multiple class names in Material UI with identical definitions

When working with traditional CSS, it is common to define shared properties between classes like this: .classA,.classB{ background-color: black; } In Material UI and using theming, the equivalent would be: styles = (theme)=>({ classA:{ ba ...

Optimizing PHP Execution Speed

I have a query regarding PHP and CRON-Jobs. I've created a PHP script that sometimes takes a long time to load due to the numerous commands it contains. To address this issue, I split the script into smaller ones to reduce the number of commands. I th ...

What is the reason for the Pointer Lock API entry displaying a significant number when the window is compressed?

Take a look at these two screenshots that illustrate the issue: The first screenshot demonstrates the correct behavior - the fullscreen mode works perfectly. However, in the second screenshot, a problem arises. Depending on the size of the browser window, ...

Linking input to radio buttons in Vue.js

When creating an edit form page, I encountered an issue where the page was not loading properly. Before the page loaded, I ran the following code: beforeMount(){ if(this.$route.meta.mode === 'edit'){ this.initialize = '/api/arti ...

Is it possible to update a specific value within an array generated from a customized search function in Suitescripts?

I have been working on a search.create function where I need to replace a value with a filter. The filter returns one or more objects which are then stored in an array. My goal is to replace a specific value with 0 if the field 'lastinv' is empty ...

Can phantomJS be used to interact with elements in protractor by clicking on them?

While attempting to click a button using PhantomJS as my browser of choice, I encountered numerous errors. On my first try, simply clicking the button: var button = $('#protractorTest'); button.click(); This resulted in the error: Element is ...

What are some ways to improve performance in JavaScript?

Can you help me determine which approach would be more efficient - using native functions of the language that involve 2 iterations or a simple for loop? The goal is to locate the index in an array of objects where the property filterId matches a specific ...

Error in Angular: Unexpected '<' token

After setting up my angular and express app using the angular-cli and express command lines, I successfully built the angular app with the ng build command. However, when attempting to serve it with the express server, I encountered the following error in ...

Issues with dynamically generating buttons using Ajax and Javascript technology

In order to dynamically create buttons based on the contents of a text file during the onload event, I have written a JavaScript function. However, despite being able to read the file and using alert messages to verify the correctness of the variable &apos ...

Guidelines for breaking down a produced string within the console.log statement in JavaScript

Seeking clarification on this inquiry. I am a complete novice when it comes to coding. Currently, I have implemented the following do while loop code taken from w3s: var text = ""; var i = 1; do { text += "The number is " + i; i++; ...

Cordova plugin for Ionic has not been defined

I am facing a challenge in my Ionic app. The issue arises when the cordova.js file containing a crucial plugin does not initialize until after the controllers.js script has been downloaded and executed. As a result, attempts to use the plugin in the contro ...

unable to activate toggleclass('d-block') for multiple radio inputs

We have multiple radio input options. function showReferral() { document.querySelector('#referral_code').classList.remove('d-none'); } <div class="form-group row d-none" id="referral_code"> <label for="referral_code"&g ...

Leveraging dynamic keys with v-for in Vue.js

In my Vuejs project, I am currently developing a reusable table component that looks like this: Table Component Structure: <template> <div> <table class="table"> <thead> <tr> ...

Selenium2: Exploring ways to retrieve error specifics after executeScript() encounters a failure

While facing certain idiosyncrasies with browsers, I often have to execute JavaScript commands during testing. Every now and then, Selenium returns an error stating that there was a JavaScript error without providing any specifics. Is there a method to re ...

Get the characteristics of the raphael pie chart

How can I access the attributes of a Raphael pie chart? I'm interested in getting attributes such as stroke color, values (excluding legend), radius, and x/y position. Here's how my pie chart is defined: pie = r.piechart(120, 140, 50, [55, 22] ...

Simplify your bootstrap Input field code by utilizing components or a similar method in Vue.js

Using a single file component with a pug template, I am faced with multiple input fields that have the same formatting. Here is an example: .input-group.input-group-sm .input-group-addon Purchase Price input.form-control(v-model='purchase_ ...

What is the best way to require users to click one of the toggle buttons in a form?

Is it possible to require the user to click one of the toggle buttons in a React form? I want to display an error if the user tries to submit the form without selecting a button. Even though I tried using "required" in the form, it didn't work as expe ...