Excessive Function Calls Detected in AngularJS Application

I'm facing a major performance issue.

I need to display details in a list, but the function is being called excessively.

Feel free to check out the demo here

Here's the HTML code snippet :

<div ng-controller="MyCtrl as ctrl">
<p>Keep an eye on your console, then click on a letter. Why does the "mysterious" function run so many times?</p>
<button ng-click="ctrl.setValue('B')">Display B</button>
<button ng-click="ctrl.setValue('C')">Display C</button>
<button ng-click="ctrl.setValue('D')">Display D</button>
  <div ng-repeat="item in ctrl.vitals track by $index">
    <p ng-click="ctrl.toggleDetail($index)" ng-bind="item.name"></p>
    <div ng-show="ctrl.myterious(item.name, ctrl.value)">This should only be displayed under {{item.name}}</div>
    <div ng-show="ctrl.display[$index]">...</div>
    <br>
  </div>
</div>

Here's the JavaScript code I've got :

var app = angular.module('myApp',[]);

app.controller('MyCtrl', [function() {
    var self = this;

    self.vitals = [
            {name:'A'},
            {name:'B'},
            {name:'C'},
            {name:'D'},
            {name:'E'},
            {name:'F'},
            {name:'G'},
            {name:'H'},
            {name:'I'},
            {name:'J'},
            {name:'K'}
    ];

    self.display = [];
    self.toggleDetail = function(id) {
        console.log("Toggle triggered");
        self.display[id] = !self.display[id];
    };

    self.value = 'B';
    self.setValue = function (val) {
        self.value = val;
    }

    self.myterious = function (a, b) {
        console.log(a + ' ' + new Date().getTime());
        if (a === b) {
            return true;
        } else {
            return false;
        }
    }
}]);

I'm looking for insights on identifying and resolving this problem, as this example is a simplified version of my actual code.

Answer №1

The function calls are all due to the ng-show binding, which runs every time the DOM is updated to decide whether or not to display the item. To minimize these function calls, it's recommended to base your ng-show bindings on something static. Check out the modified example below:

JSFiddle Example

self.vitals = [
      {name:'A', mysterious: false},
      {name:'B', mysterious: true},
      {name:'C', mysterious: false},
      {name:'D', mysterious: false},
      {name:'E', mysterious: false},
      {name:'F', mysterious: false},
      {name:'G', mysterious: false},
      {name:'H', mysterious: false},
      {name:'I', mysterious: false},
      {name:'J', mysterious: false},
      {name:'K', mysterious: false}
    ];

self.setValue = function (val) {
        self.vitals.forEach(function(obj) {
         obj.mysterious = obj.name == val
         })
        self.value = val;
    }

<div ng-repeat="item in ctrl.vitals track by $index">
    <p ng-click="ctrl.toggleDetail($index)" ng-bind="item.name"></p>
    <div ng-show="item.mysterious">
        This content should only be displayed for {{item.name}}  
   </div> </div>

If there is a genuine business requirement for dynamic visibility calculation, go ahead with it but use it judiciously. Excessive function executions can lead to performance issues. It's advisable to design your visibility logic around static bindings whenever possible.

Answer №2

The reason behind this behavior is that AngularJS re-runs the ng-repeat loop whenever there is a change in the data (in this case, ctrl.vitals) or any other flag, variable, etc. used within the loop.

In this scenario, your mysterious element is contained within an ng-if, which means it must be processed for each iteration of the loop.

Additionally, there are more nuances to consider, as detailed in this informative article: Facing Issues with AngularJS? Check out This Article

Answer №3

Your function may be called more frequently than expected, as ng-repeat is a directive that can run multiple times. This behavior is typical and nothing to worry about.

For further insight into why functions are executed multiple times, check out this helpful explanation: Why is ng-style function applied twice?

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 automatically inserting a "read more" link once text exceeds a certain character count

Currently utilizing an open-source code to fetch Google reviews, but facing an issue with long reviews. They are messing up the layout of my site. I need to limit the characters displayed for each review and provide an option for users to read the full rev ...

Attempting to implement a disappearing effect upon submission with the use of JavaScript

I am currently working on implementing a disappearing form feature for a small web application. The idea is that once the initial form is submitted, it will be replaced by a new form. While my current code somewhat works, it only lasts for a brief moment b ...

There is an issue with Node/Express not accurately updating the data model

I recently went through a tutorial on creating a RESTful API with Node.js and MongoDB. While it worked well overall, I encountered a few issues. My Player model is as follows: var player = new mongoose.Schema({ name: String, email: String, score: String } ...

retrieving an element from a collection of objects

For a project utilizing the openweather api, I encountered fluctuating data based on the time of day it is viewed. My goal is to loop through the first 8 objects to identify a dt_txt value of 12:00:00. Once found, I intend to store this result in a variabl ...

When a named capture group is included in the regex of a GET path, Express crashes with the error message: "Cannot read property 'name' of undefined at Layer

I am looking to process a GET request and extract specific information from the URL. Let's consider this scenario: const REGEX_QUERY = /^\/?house\/(?<street>[a-z]+)\/(?<house>[0-9]+)$/i; const REGEX_QUERY_NO_NAMES = /^\ ...

What is the best way to update the values of an array of object properties using an input form in JavaScript?

I'm currently learning node.js, express.js, and handlebars I am working on creating two forms for a blog/news page: an add form and an edit form. /addproject: app.get('/addproject', function(req, res) { res.render('addprojec ...

jPlayer calculates the "duration" as 1,440 minutes on iOs devices for all mp3 files

My homemade webpage is designed for playing mp3s and viewing pdfs. I'm using jPlayer v 2.9.2 to play the mp3s, which works fine on PC but encounters issues on iPhone. The duration values are incorrect, showing "1439:59" remaining for all files, causin ...

What is the process of displaying text within a link?

I have a basic webpage where I want the text to display from a link. Here is my website: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Encyclopedia</title> <link href="test.css" re ...

Is it possible to generate distance between 2 elements without utilizing padding or margin?

In my React Native project, I'm currently working with 2 inline buttons - the search and add buttons: https://i.stack.imgur.com/tKZrf.png I'm looking to add some spacing between these buttons without impacting their alignment with the left and ...

Angular Components unexpectedly lose background transparency when using Transparent-Background-PNG in the foreground

Hey there! I'm currently working on a landing page and I have this amazing idea to use a stunning picture of clouds with a transparent background layered over a beautiful landscape. The only problem is that when I try to implement it, the transparency ...

Can Google Map markers be added onto Node.js and then transferred to Angular?

Is there a way to render Google Maps on the server side? For example, can I place markers on the map from MongoDB and then pass the rendered map to the client for display along with all of the markers? I want to show a map with multiple markers on the cli ...

What could be causing my page width to only expand to 100% when using "fit-content"?

After searching extensively, I'm unable to find a solution that fits my current issue. My goal is to construct a practice ecommerce website using React. One of the components I have is a header which I'd like to occupy 100% of the screen width, c ...

Show the current time of a track using VueJS

Is there a way to have the time continuously update itself without needing to click on anything? When I press play, I want the seconds to automatically start updating from 0:00 until the end of the audio track. Currently, the time only updates when clicked ...

Locate specific phrases within the text and conceal the corresponding lines

I have a JavaScript function that loops through each line. I want it to search for specific text on each line and hide the entire line if it contains that text. For example: <input id="search" type="button" value="Run" /> <textarea id ...

Tips for utilizing window.scrollTo in tandem with react/material UI?

I have a simple functional component that displays an alert panel with an error message under certain conditions. The issue I am facing is that when the alert panel is rendered due to an error, it might be off-screen if the user has scrolled down. To addre ...

Redis VS RabbitMQ: A Comparison of Publish/Subscribe Reliable Messaging

Context I am working on a publish/subscribe application where messages are sent from a publisher to a consumer. The publisher and consumer are located on separate machines, and there may be occasional breaks in the connection between them. Goal The obj ...

Crisscrossed JavaScript Object: recursion and "intricate" conversion (using lodash)

Apologies for the complexity of this example; I've condensed it as much as possible to demonstrate what I'm aiming for I have a complicated structure that needs to be traversed and transformed based on certain conditions. Here's a brief exa ...

JavaScript: Transforming binary information from Uint8Array into a string causing file corruption

In my attempt to send a video file to a server in chunks using a basic jQuery $.ajax call, I followed these steps: Utilized the slice() method on the file object to extract a chunk Used FileReader.readAsArrayBuffer to read the generated blob Generated a ...

Discover the position of a dynamically added element

Is there a way to identify the specific dynamically added checkbox that was clicked, whether by index or name? I came across a similar question with a solution in this JSFiddle: JSFiddle Instead of just displaying "clicked", I would like it to show someth ...

Executing a POST Request from AngularJS to a server-side script

Currently, I am in the process of developing a web application using Yeoman tools with AngularJS. However, I have encountered a challenge when trying to send a POST request to a server-side script from a controller. Below is the snippet of code from my con ...