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

Using AJAX to communicate with a MySQL database and create a countdown timer using JavaScript

I have been trying to display data from a database using Ajax and incorporate countdown timers with times also fetched from the same database. It has been a struggle for me for almost 24 hours now. You can check out the main code here where you will notic ...

Tips on sorting a FileList object selected by a directory picker in JavaScript/TypeScript

I need to filter or eliminate certain files from a FileList object that I obtained from a directory chooser. <input type="file" accept="image/*" webkitdirectory directory multiple> Within my .ts file: public fileChangeListener($event: any) { let ...

Tips on maintaining the numerical value while using JSON.stringify()

Having trouble using the JSON.stringify() method to convert some values into JSON format. The variable amount is a string and I want the final value in JSON format to be a number, but it's not working as expected. Even after applying JSON.stringify(), ...

Node.js: implementing method overriding

I'm currently exploring the most effective method to override a function in a custom module using node.js. As part of my project, I am developing a custom middleware that will assist me in automatically loading various custom modules such as security ...

Can all AngularJS modules be seamlessly integrated with Browserify?

After discovering a module called angular-timeline, I proceeded to install it by running npm install angular-timeline --save. Following that, I used the command require('angular-timeline'). var angular = require('angular'); require(&ap ...

Using Vue with Firebase to fetch a specific range of data starting from a particular record and ending at the

I am looking to retrieve all records from a certain record to the very last one in my database. ref.orderByChild("date").equalTo("19/11/2020 @ 19:50:29").on("child_added", (snapshot) => { console.log(snapshot.va ...

Adjusting attention to the switched element

I am currently developing an inline editing feature using AngularJS. Here is the code snippet from my Controller: $scope.toggleEditor = function(){ $scope.editorEnabled = !$scope.editorEnabled; //toggle editor view //struggling with this part $time ...

Issue with the Animated Skill Bar not functioning properly when scrolling

I've been trying to implement an animated skill bar in my Portfolio using JQuery, but I'm facing some challenges. Despite following various tutorials, the code doesn't seem to work as expected. I've tried calculating section scroll posi ...

Execute the identical script in NPM, but with various parameters each time

Recently, I created a nodeJS script with a parameter. Currently, using npm start allows me to pass arguments and run my script successfully. However, I'm now faced with the challenge of passing multiple arguments to npm start in order to run multipl ...

What is the method for specifying a JSON object within a DOM element's `data` attribute?

In an attempt to store JSON data within a dataset attribute, I encountered the following HTML structure: The appearance of the HTML is as follows <div data-switch="true" data-json="{'key1': 'value 1'}, {'key2': 'valu ...

Check out the HTML display instead of relying on console.log

Need help displaying the result of a JavaScript statement in an HTML page instead of console.log output. I am new to coding! Here is the JS code snippet: $.ajax({ url: 'xml/articles.json', dataType: 'json', type: ...

Adaptable material for collapsible panels

I'm facing a challenge with implementing an accordion menu. My goal is to have a 4 column layout that transforms into an accordion menu when the browser width is less than 600px. It almost works as intended, but there's a glitch. If you start at ...

Combining the Angular Material Design mdToolbar with the Ionic ion-nav-bar: A Match Made

Currently, I am in the process of creating an application using Ionic and Angular Material. However, I am facing a challenge with getting Ionics back button to function properly when it is used within the mdToolbar directive of Angular Material. To illust ...

It seems like there may be an issue with the React Table Pagination in reactjs

As a newcomer to React JS, I have been utilizing react-table to create a component that can filter, sort, and paginate sample data from a JSON file. If you are interested in the tutorial I am following, you can find it here: Currently, I am encountering ...

Ngrx/effects will be triggered once all actions have been completed

I've implemented an effect that performs actions by iterating through an array: @Effect() changeId$ = this.actions$.pipe( ofType(ActionTypes.ChangeId), withLatestFrom(this.store.select(fromReducers.getAliasesNames)), switchMap(([action, aliases ...

Trigger click functions sequentially to display elements after specific actions are taken

Is there a way to make jQuery listen for clicks only at specific times? It seems that when I add event listeners, like $("#box").click(function(){, they are executing before the code above them finishes running. Let's say I have two boxes that should ...

Using a variable as a URL parameter in a jQuery ajax request: tips and tricks

$.ajax({ type:"POST", url:"hostname/projfolder/webservice.php?callback=statusReturn&content="+str_table, contentType: "application/json; charset=utf-8", crossDomain:true, dataType:'jsonp', succe ...

Various conditional statements based on the dropdown menu choice

I currently have a basic dropdown menu on my webpage that enables users to switch between viewing Actual or Planned dates/times in a table (I am utilizing the controller as syntax): <select ng-model="trip.viewType"> <option value="actual"> ...

extract objects from an array of objects based on a specified array

Within my JSON array, I have data structured like this: const data = [ { "uniqueId": 1233, "serviceTags": [ { "Id": 11602, "tagId": "FRRRR", "missingRequired&quo ...

Achieve text length that does not exceed the specified limit dynamically

Is it possible to determine the length of the visible portion of text that overflows (or calculate the size of the overflow for further processing) using CSS or JavaScript? If so, can this calculation be done dynamically (such as on window resize)? The g ...