Comparison between using expressions in HTML tags and utilizing a controller

When working in Angular, let's say I have the following functions:

$scope.getA= function(){
// do los stuff
return result;
};
$scope.getB= function(){
// do los stuff
return result;
};
$scope.getC= function(){
// do los stuff
return result;
};
//$scope.getD(), $scope.getE()...    

I have some HTML elements with rendering logic dependent on complex conditions. Apart from readability, is there a difference in performance (render speed) between the two code snippets below? I noticed that the first one takes longer to display all elements compared to the second, but I am unsure if this observation holds true...

    <div ng-if="getA()&&(getB()== "text"?getC():getD())||getE()">hello</div>
//more div tags like this...

and

    $scope.show = function(){
       var bar = getB()== "text"?getC():getD();
       return getA()&&bar||getE();
    }
    //more functions like this...
    <div ng-if="show()">hello</div>
//more div tags like this...

Answer №1

Elucidates

The ngIf directive establishes a new scope through prototypal inheritance. This means that if the attribute is not found in the ngIf scope, it will search through its prototype objects chain to locate that particular attribute, granting you control over $scope.

Now, let's revisit your code examples:

ng-if="getA() && (getB() == 'text' ? getC() : getD()) || getE()"

and

ng-if="show()"

In the first example, when executing ngIf, access to the parent scope occurs 4 times (

getA, getB, either getC or getD, getE
functions).

In the second example, access only happens once (show function), resulting in a performance discrepancy.

Summary

For your situation, define a method in the controller and utilize it within the ngIf directive. However, contemplate avoiding the use of ngIf altogether as it will escalate $$watcher counts. Instead, carry out DOM manipulation (refer to angular.element for more information) without increasing $$watcher counts.

Answer №2

Is there any documentation available that explains how to evaluate a function within an HTML tag?

The directive ng-if utilizes $watch to assess the expression. 1

According to the documentation:

 * @ngdoc method
 * @name $rootScope.Scope#$watch
 * @kind function
 *
 * @description

It registers a callback listener to run every time the watchExpression changes.

  • The watchExpression is executed on each call to ng.$rootScope.Scope#$digest and should return the value to be watched. (watchExpression shouldn't change its value when executed multiple times with the same input as it may be executed several times by ng.$rootScope.Scope#$digest. In other words, watchExpression should be idempotent.

-- AngularJS $rootScope.Scope API Reference -- $watch

$digest();

This function processes all watchers of the current scope and its children. As a watcher's listener can alter the model, $digest() continues calling the watchers until no more listeners are triggered. This could potentially result in an infinite loop. If the number of iterations exceeds 10, an error 'Maximum iteration limit exceeded' will be thrown.

-- AngularJS $rootScope.Scope API Reference -- $digest

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

Upgrade to a more stable configuration version for Nodemailer as the current configuration is not supported. Consider down

I'm currently utilizing Nodemailer version 2.6.4 with Node version 6.9.1 var nodemailer = require("nodemailer"); var wellknown = require('nodemailer-wellknown'); var transporter = nodemailer.createTransport("SMTP",{ service: "yahoo", ...

Tips for triggering an error using promise.all in the absence of any returned data?

I'm dealing with an issue in my project where I need to handle errors if the API response returns no data. How can I accomplish this using Promise.all? export const fruitsColor = async () : Promise => { const response = await fetch(`....`); if( ...

AngularJs Directive continuously returns undefined

Exploring angularjs directives for the first time has been quite a challenge. I can't seem to figure out why my directive isn't working properly as the scope.durationTimeInput always returns undefined no matter what I try. (function () { 'u ...

Struggling with Angular Material not functioning properly? All features seem to be included

I am having trouble with my website being split into different parts. I have included the CSS inside the head tag and the JS in the body, but it is still not working properly. - setup and I have also tried the following: <html ng-app="StarterApp"> ...

Tips for assigning multiple Angular2 variables in Jquery on change

I am having trouble assigning more than one variable in jQuery within Angular2. Here is my current code: jQuery('.source-select').on('change',(e) => this.updateForm.value.sources = jQuery(e.target).val().split('--')[0]); ...

Unable to transmit information using Postman for registration API

I have been struggling to send data via a POST request to the register API, but for some reason, the data is not being transmitted. I have tried adjusting the settings on Postman, tinkering with validation rules, and various other troubleshooting steps, ye ...

Insert a new element at the current scroll position without disrupting the existing scroll or view

My goal is to replicate the functionality of the Twitter Mac client. I have a scrollable box with a fixed height and multiple blocks inside. I want to add a new block before all the others, but keep it invisible to the user so they have to scroll to the to ...

When embedding HTML inside an Angular 2 component, it does not render properly

Currently, I am utilizing a service to dynamically alter the content within my header based on the specific page being visited. However, I have encountered an issue where any HTML code placed within my component does not render in the browser as expected ( ...

Enabling the use of jQuery with Angular instead of JQLite

According to the angular DOCS, if jQuery is available, angular.element is an alias for the jQuery function. If jQuery is not available, angular.element delegates to AngularJS's built-in subset of jQuery, known as "jQuery lite" or jqLite. In an attemp ...

The project is not being recognized by 'webpack' when running within it

Every time I attempt to execute 'webpack' in my project, the command line shows me this error message: 'webpack' is not recognized as an internal or external command, operable program or batch file. I have installed webpack using th ...

Encountering a bad request error while attempting to update a numeric value in MongoDB

I attempted to update a single element in mongodb, specifically a number value. Below is the request sent to the DB: const handleDelivered = (num) =>{ const total = service.quantity; const final = parseInt(total) + num; console.log(tota ...

Angular filter is designed to search for elements that contain a specific value, rather than only those that are an exact match

I am currently trying to relate rules to fields using the 'filter' filter in Angular. You can see an example of this implementation here: http://plnkr.co/edit/dQiv5lRzhQNjXZ6pVdWO?p=preview The code I am using for this purpose is as follows: &l ...

React js component fails to interact with Jquery plugin

I'm interested in combining React with jQuery in the following way: Let's say I have a textarea that is generated by React: var textarea = React.createClass({ render : function(){ return <textarea id="mytextarea"></textarea&g ...

Integrate haptic feedback in ReactJS

Trying to incorporate vibration functionality into my code, specifically in a React environment. I've experimented with various JavaScript methods but haven't had success yet. Here's what I've attempted within a function: window.naviga ...

Vue3: Pinia store data not being received

Having trouble retrieving Pinia data using the Composition API after a page reload? I'm utilizing Vue to parse fetched JSON data. Despite being new to the Composition API, I can't pinpoint what's causing the issue even after going through th ...

Step-by-step guide on running two JavaScript codes sequentially to ensure accurate results

I am currently working on an MVC project where I need to display the user's current location city in the top right corner of a webpage. The first javascript code fetches the city name, and the second one retrieves the weather conditions of that city. ...

Unfortunately, the jquery Calendar plugin is malfunctioning

After much consideration, I decided to implement this calendar plugin on my website Plugin Unfortunately, it isn't working as expected. I am encountering the following error: $(...).pignoseCalendar is not a function at HTMLDocument. (Index ...

Styling JSON format in Node.js

I have a code snippet that queries a database and outputs the information in JSON format: connectionpool.getConnection(function(err, connection) { if (err) { console.error('CONNECTION error: ',err); res.statusCode = 503; ...

Using the phrase "activating a 'sister' function"

I'm dealing with some code that resembles the following: var viewService = function () { ... return { ... ,isAbsolute: function (view) { ... } ... ,removeAbsoluteViews: function () { ... } } }; }; My goal is to ...

Encountering difficulties in linking socket.io node server to react frontend. Receiving a "404 (Not Found) error for "POST http://localhost:3000/socket.io/?EIO=3&transport=polling&t=MoHNIJT"

I have set up a frontend using React and a backend with Express Node.js. I am utilizing socket.io for communication between the client and server. Upon loading the React page, I encounter an error message that repeats every second: Failed to load resourc ...