Accelerating the processing speed of Angular's $compile function

I'm currently putting together a template against a fresh scope:

var scope = _.assign($rootScope.$new(true), {
  foo: 1,
  bar: 2
})
var element = angular.element('<my-element foo="foo" bar="bar"></my-element>')
$compile(element)(scope)
element.appendTo(container)

Upon conducting a basic analysis, it appears that the slowest part of this code is $compile, taking approximately 1ms per compilation. I am required to compile around 100 elements concurrently as the user scrolls.

Although there are numerous optimizations possible to expedite compilations after the initial round of $compiles, my goal is to hasten the very first set of 100 compiles. Furthermore, I aim to retain the templates within Angular and refrain from injecting raw HTML.

Any suggestions?

Edit: Reposting my comment from below here for better visibility in case someone comes across this thread in the future:

It finally clicked for me. By passing a function as the second argument to $link, Angular will clone the node for you. If not, it will reuse the same node with every call to $link. In either scenario, you can access the returned node synchronously (as the return value of $link) or asynchronously (within your callback). This aspect of the API seems flawed. I have submitted an issue on Angular's tracker here - github.com/angular/angular.js/issues/11824

Answer №1

If you have elements that share the same structure but differ in the scope they are linked to, it is recommended to $compile the template just once and then use link for each of the 100 elements with their respective scopes.

var myElement = angular.element('<my-element foo="foo" bar="bar"></my-element>');
var myElementLinkFn = $compile(myElement);


// The "items" variable contains data used to create myElement elements
angular.forEach(items, function(item){
   var newScope = $scope.$new(true);

   newScope.foo = item.foo;
   newScope.bar = item.bar;

   myElementLinkFn(newScope, function(clone){
      container.append(clone);
   })
});

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

A guide on serializing multiple objects returned from a loop using JSON.stringify

My MVC code involves adding multiple travelers objects to the travelers array generated in a loop, and then using JSON.stringify on them. return amadeus.booking.flightOrders.post( JSON.stringify({ 'data':{ 'type ...

Unlocking the Potential of NextJS with Dynamic Page Export - Say Goodbye to Static HTML!

I am attempting to export my NextJs project based on the official documentation provided. However, it seems that I can only export it into static HTML. Is there a way to export it into dynamic pages where user-submitted data is updated in real time, simil ...

Strategies for manipulating the position of an SVG polyline

Is there a way to move the chevron symbol to the beginning of each accordion header instead of it being on the right side of the words? Any help with this would be appreciated. The code snippet is provided below. Please advise on how to reposition the pol ...

AngularJS Text Size Adjuster

I've managed to change the font and font size separately for different texts, but now I want to apply both functions to one text. How can I achieve this? Below is my HTML code: <div ng-controller="StylesCtrl"> <select ng ...

Is there a way to set the image result retrieved from the API call as the background image for my app?

In my current project, the user is able to input a city and the background of the page changes to display an image of that specific city. This image is obtained through an API call to Pixabay API, with the result stored in a variable named "background". Ho ...

Adjust the badge's color based on the status retrieved from the jQuery AJAX call

I've been working on retrieving data from an endpoint through a get request, and I'm looking to adjust the color of the request status based on the response. $.ajax({ type: 'GET', url: 'api/v1/service/tax', succe ...

Identifying the selected element within a THREE.js object

I've created a sphere with a background image, and placed the camera inside to create a panoramic effect when the sphere rotates. Now I'm looking to detect when a user clicks on the sphere using a three.js example: var intersects = ray.intersec ...

Tips for utilizing the pixel-based margin and padding properties in Bootstrap 4

Can Bootstrap's margin and padding properties be used with pixel values instead of rems in Bootstrap 4? For instance, if I want a div to have a margin-left of 20 pixels, can I do the following: <div class="container ml-20">Hi</div&g ...

Pause page scrolling temporarily in JavaScript while allowing the scrollbar to continue scrolling until the pause is lifted

I'm currently working on achieving a similar effect to the one found on this website: . On that site, as you scroll down, the 'HELLO' text moves to the side. I've managed to do that part successfully, but I'm facing an obstacle reg ...

HTML - Transforming JSON data into a table

I'm having trouble converting JSON data into a table format. Although everything seems to be in order, I am unable to view the values on my table. Here is the code I am using to convert JSON to a table: $(function() { var my_data = &ap ...

Create a distinct variable name for opening a modal within an *ngFor loop

I need help creating a unique variable called share within the *ngFor loop so that I can open a single modal. <li *ngFor="let gallery of galleries; let i = index"> <div class="gallery card" > <div class="sh ...

Tips for clearing a saved password in a browser using Angular.js and Javascript

There is an issue with the password and username fields in my Angular.js login page. When a user clicks on the 'remember me' option in their browser after logging in, the saved username and password are automatically displayed in the respective f ...

mandatory data fields for an HTML form

I'm having some trouble creating an HTML form with mandatory input fields. The code I have so far is shown below: <div class="col-sm-6"> <label for="city" class="form-control">City ...

Modifying CSS content attribute in real-time

A colleague of mine has rented a webshop from a company. They have the option to select different templates and are also able to customize the CSS and add Javascript snippets. They reached out to me for help with making some modifications, but there's ...

Accessing multiple nested objects in Javascript using a string as an object reference

One thing I am aware of is the ability to define an object reference from a string, such as this: obj['string'] This essentially translates to obj.string. My query arises when trying to extend this beyond the first object value. This is what I ...

What is the best way to access the Node.js HelloWorld File that I created with a .js extension?

I am currently going through the materials at "NodeBeginner.org". Despite my limited experience with command line, I am struggling to execute my first file. The only success I've had so far is running "console.log('helloworld');" by typing ...

Personalized 404 Error Page on Repl.it

Is it possible to create a custom 404-not found page for a website built on Repl.it? I understand that typically you would access the .htaccess file if hosting it yourself, but what is the process when using Repl.it? How can I design my own 404-not found p ...

The emulator failed to launch because it could not find any emulators listed as an output of the `emulator -list-avds` command

Hello everyone, I've recently ventured into the world of React Native and managed to successfully install and launch the emulator. However, I encountered a problem when attempting to run the command react-native run-android. The console output display ...

Utilizing Jquery for Targeting a Specific div Element and Implementing CSS Styling

In my collection of styles, I have some interesting ones like: .line{} And also: .line:focus{} Each style has its own individual charm. I am looking to use jQuery to focus on a div with the class .line and change its style to .line:focus. However, eve ...

The React date picker is experiencing a delay when opened with a click

A peculiar problem has arisen with react-datepicker. I have successfully integrated my datepicker with Redux Form, and the code is as follows: <DatePicker customInput={<CustomDateInputNew {...props} />} onChange={date => { props.input. ...