At what precise moment does the ng-checked function get executed?

When utilizing AngularMaterial, I have implemented ng-checked in the following manner:

<md-list>
    <md-list-item ng-repeat="option in options">
       <p> {{ option }} </p>
       <md-checkbox class="md-secondary" aria-label="{{$index}}" ng-checked="exists($index)" ng-click="toggle($index)"></md-checkbox>
    </md-list-item>
</md-list> 

Here is my exists function:

$scope.exists = function (optionNum) {
    console.log('Inside $scope.exists. Option: '+optionNum);
};

I also have a timer function:

function updateTimer() {
    var onTimeout = function(){
      mytimeout = $timeout(onTimeout,1000);
    }
    var mytimeout = $timeout(onTimeout,1000);
}

As a result, the $scope.exists function is being called every second. Can someone provide insights into the relationship between ng-checked and $timeout, as well as how to prevent this continuous calling?

Answer №1

In a single word, the reason is: digest cycle. Your function is linked to the view, so each time the digest cycle occurs, these expressions are evaluated for a dirty check to determine if the corresponding DOM needs updating. This process is not exclusive to angular material but rather a fundamental part of Angular's implementation. In your scenario, calling $timeout repeatedly triggers a digest cycle after each timeout execution, conducting a dirty check.

The approach you currently have is acceptable, however, when you bind a function to the DOM (as part of view binding, interpolation, property state attributes, or even DOM filters - excluding events), it's crucial to be mindful that extensive operations within that function can potentially slow down the entire application as it scales. It may also become challenging to troubleshoot and refactor as the app grows in size and issues arise. Whenever possible, opt to bind to a property instead of a function. Even when binding to a property, Angular's $parse still generates a getter function for it and includes it in the $$watchers queue for dirty checking during each digest cycle, albeit being a simpler getter function.

Thus, in your case, consider binding ng-checked to a property:

..ng-checked="doesExist"

And update the property doesExist whenever necessary. By doing this, instead of repeatedly verifying for existence, you explicitly adjust the corresponding property upon the occurrence of a relevant event, thereby making the logic more straightforward.

Answer №2

The ng-checked directive, along with many others in Angular, relies on watches for their functionality. Whenever a digest cycle is triggered, all of the watchers are evaluated, including the function associated with the directive. Therefore, every time $timeout runs, it initiates a new digest cycle and evaluates all watchers, ensuring that the view stays updated with the data from your controllers and directives.

However, having too many watchers or complex functions can lead to performance issues. It's advisable to keep your logic simple and efficient, returning true or false quickly. Avoid setting watches on everything to optimize performance.

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

Can the useNavigation hook be used to navigate to a class component in React?

How can I use the useNavigation hook to navigate to a class component? Here is my class: export default class AzureLogin extends React.Component I want to navigate to AzureLogin from Screen1. What is the correct way to achieve this? import { useNavigati ...

Setting a cookie in a browser using an AJAX response: A step-by-step guide

When utilizing a Javascript function with jQuery to send a POST request to a web service, the response from the web server includes a header "Set-Cookie: name=value; domain=api.mydomain.com; path=/", along with a JSON body. However, despite this expected ...

Comparison of jQuery, AngularJS, and Node.js

I'm a beginner in web development and I have some basic knowledge: HTML - structure of websites CSS - design aspect JavaScript - for adding interactivity Now, what exactly is jQuery, AngularJS, and Node.js? Upon researching, I discovered that jQue ...

Angular 6 - Consistently returning a value of -1

I'm facing an issue with updating a record in my service where the changes are not being reflected in the component's data. listData contains all the necessary information. All variables have relevant data stored in them. For example: 1, 1, my ...

Non-IIFE Modules

Check out this discussion on Data dependency in module I have several modules in my application that rely on data retrieved from the server. Instead of implementing them as Immediately Invoked Function Expressions (IIFEs) like traditional module patterns ...

Is Jquery Mobile's Table lacking responsiveness?

I have implemented a basic table from the jQuery Mobile website on my page. Take a look at the HTML code below: <div data-role="page" id="mainPage"> <div data-role="content> <table data-role="table" id="my-table" da ...

While working on a project in React, I successfully implemented an async function to fetch data from an API. However, upon returning the data, I encountered an issue where it was displaying as a

I am working with React and TypeScript and have the following code snippet: const fetchData = async () => { const res: any = await fetch("https://api.spotify.com/v1/search?q=thoughtsofadyingatheist&type=track&limit=30", { met ...

What is the best way to keep an image fixed at the bottom, but only when it's out of view in the section

There are two buttons (images with anchors) on the page: "Download from Google Play" and "Download from App Store". The request is to have them stick to the bottom, but once the footer is reached they should return to their original position. Here are two ...

Is it possible to recognize when the mouse button is held down and the cursor is outside the viewport by using mouseleave detection?

Is there a way to detect when a user moves the mouse outside of the view-port, even if they are holding down the mouse button (for example, if the mouse is on the browser address bar)? In the code below, I am currently using mouseout and mouseleave to det ...

When initiating the Grunt Express Server, it prompts an issue: Error: ENOENT - the file or directory 'static/test.json' cannot be found

I'm currently in the process of updating my app to utilize the Express Node.js library. As part of this update, I have made changes to my Grunt.js tasks to incorporate the grunt-express-server package. However, after running the server successfully, I ...

Transmitting the character symbol '&' within a string from Angular to PHP

My goal is to transmit a string, such as "the cat & the dog", from Angular to PHP using GET method. I have used encodeURI(note) in Angular and in PHP $note = $_GET['note']; $note = mysql_real_escape_string($note); However, when it gets inse ...

What is the best way to integrate a Next.js Image component with a set width and an adaptable height in order to maintain the image's proportions?

This code snippet uses ChakraUI styling and retrieves images from SanityCMS: <Box w="500px" h="500px" bg="red"> <Image src={allArtPieces[0].imageUrl} alt={allArtPieces[0].title} width="500px" ...

Tips for making immutable state changes in React

Is there a way to update specific content in the state without affecting all other data stored in the state? Just to provide some context: The function below is executed within another "handleChange" function that takes the event as input and assigns the ...

Integrate jquery into an expressJs application

Is there a way to include jQuery in the express app.js file? I need to use jQuery within app.js to make modifications to the HTML file. For example: app.js const express = require('express') const app = express() const $ = global.jQuery = re ...

What is the best method for injecting a factory dependency into an angular controller?

Situation:- I have a factory named testFactory. Up until now, I was defining my controller like this: app.controller('testCtrl',function($scope,testFactory) { testFactory.Method1(){ //working fine} } However, before minimizing the file, I def ...

How to Create a DataTable Responsive Feature Where All Columns Collapse on Click, Except the Last One?

I am currently utilizing the DataTables library to generate a responsive table. I am aiming to create a feature where all columns in the DataTable can toggle between collapse and expand states when clicked, with the exception of the last column. Below is a ...

Guide on disabling withCredentials in an angularjs and expressjs project

$scope.checkStatus = function() { $http({url:'url', method:"GET", withCredentials: false, headers:{ 'Authorization': 'Token ' + token, } }) .success(function(result) { console.log("Data ret ...

What are the steps for integrating mongoDB with an angular2 application?

I currently have my angular2 & mongoDB setup successfully. While I've managed to read JSON files using the HTTP service, my goal is to create a fully functional application with database connectivity as well. I'm seeking advice on how to con ...

Leveraging thousands of on() event listeners in Firebase demonstrates exceptional design

We are looking to perform operations on our Firebase database and modify data based on user input from their mobile devices by changing a flag. Currently, we are using the `on()` method to listen to specific flags within each user's node. This listen ...

Why use getElementById(id) to obtain an element in JavaScript when it already exists in the JS?

Recently, I have observed that a reference to an HTML element with an id can be easily accessed in JavaScript by using a variable named after that id (jsbin). What is the reason for this behavior? Why do we need to use getElementById(id) when we could sim ...