Delving into the prolonged compilation time and deciphering the root cause of the latency issue within AngularJs

Lately, I've become fixated on a particular issue that I need your help solving. My task at work involves creating a list of posts with comments, each post having the states of view, edit, and delete.

To manage the posts and comments, I've developed directives for Post and Comment, as well as PostList and CommentList directives. The code for Post and Comment is quite similar. You can view the code here: http://plnkr.co/edit/k77kdSwPnqY4jR5EY7N4?p=preview

app.directive("Post", function ($templateCache, $compile) {
    function getTemplate(mode) {
        switch (mode) {
            case "create":
                return "createPost.html";
            case "view":
                return "viewPost.html";
            case "delete":
                return "deletePost.html";
        }
    }

    var defaultMode = "view";

    return {
        scope: {},
        restrict: "AE",
        compile: function (elem, attrs, transclude) {
            return function ($scope, $element, $attr) {
                function updateTemplate() {
                    $element.html("");
                    $compile($templateCache.get(getTemplate($scope.mode)).trim())($scope,   function (clonedElement, scope) {
                        clonedElement.appendTo($element);

                    });
                }

                $scope.mode = $attr.mode || defaultMode;

                $scope.$watch("mode", updateTemplate);
            }
        }
    }
})

The templates like viewPost.html contain numerous bindings and directives such as ng-show, ng-src, ng-bind-html-unsafe. The viewPost.html includes the commentList directive for displaying comments. When compiling a Post, the comments for each post are automatically compiled.

As I render a list of 20 posts with multiple comments, the page takes over a second to load, making the webpage unresponsive during this time.

I'm starting to doubt if my chosen structure is the right way to go. Is Angular the best fit for this task?

Despite my love for Angular, I'm feeling disheartened now and worried that it might not be suitable for this project. Can you help me regain my confidence and love for Angular by pointing out what I may have done wrong?

Here is the link to my project that I'd appreciate your insights on:

login: [email protected]

pass: 123456

Please note that the content is in Russian. You can visit this page to experience the current sluggishness: .

Answer №1

I took a unique approach to this problem and found it to be both efficient and effective.

Instead of using directives, I utilized recursive templates to achieve the desired outcome.

Here is a snippet of the template with CSS classes included for clarity:

<script type="text/ng-template" id="responsetemplate">

<div class="reply">

    <div class="wrapper">
        <div class="questioninner">
            <div class="mainreply">
                <p ng-show="!model.edit" ng-click="edit(model)" ng-bind="model.message"></p>
                <div ng-show="model.edit">
                    <textarea ng-model="model.message"></textarea>
                    <button ng-click="save(model)">save</button>
                    <button ng-click="cancel($parent,model)">cancel</button>
                </div>
            </div>
            <div class="replyfooter">
                <div class="actions">
                    <div ng-show="!model.edit">
                        <a ng-click="edit(model)">edit</a>
                        <a ng-click="delete($parent,model)">retract</a>
                        <a ng-click="reply(model)">reply</a>
                    </div>
                </div>

            </div>

        </div>
    </div>

    <div>
        <div ng-repeat="model in model.responses" ng-include="'responsetemplate'"></div>
    </div>
</div>
</script>

This template displays a question and recursively shows all responses to the question using ng-repeat and ng-include.

I store my data in the 'model,' which includes the question and an array of responses with additional nested responses.

The example also includes functionality for editing, deleting, and replying to responses.

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

Cease an if condition in AngularJS JavaScript

I am facing a situation where I have an if statement that needs to halt execution but only after certain processes have been completed. This if statement is enclosed within a forEach loop in an Angular context. angular.forEach($scope.obj, function ( val ...

Error: The document object is not defined when attempting to access it within a

<script type="module" src="/scripts/navbar.js"></script> <script> async function fetchContent(e) { e && e.preventDefault(); const response = await fetch('https: ...

Controller Not Deserializing Ajax File Upload in MVC 5

There seems to be an issue with deserializing the data sent using the multipart/form-data type within an MVC 5 project. Despite appearing valid in Fiddler, the data is not being mapped into the controller method. While debugging, it is evident that all par ...

Is it achievable to have a background image cover size with a responsive rollover effect?

I’m currently facing a unique challenge where I want to have an image as the background of my website, with the size set to cover the entire screen. On this background image, there are elements like buildings that I want to interact with when hovered ove ...

What is the best way to change the first letter of a string to uppercase in JavaScript?

Creating a form with 10 textboxes and one button, I want the first letter of any text entered into a textbox to be capitalized when the user loses focus on that specific field. To achieve this functionality, JavaScript seems like the most suitable option. ...

Trouble with accessing a function in Ionic FabricJs

ionViewDidEnter(){ this.initializeCanvas(); } initializeCanvas(){ canvas.on('mouse:down', function(e){ this.handleCanvasMouseDown(e); }); } handleCanvasMouseDown(e){ console.log(this.lock); console.log(this.pausePa ...

What are the best scenarios for implementing anonymous JavaScript functions?

I am currently exploring the reasons behind using anonymous JavaScript functions. Can you list out the distinctions between these functions? Describe scenarios where each function would be appropriate to use. var test1 = function(){ $("<div />" ...

What is the appropriate overload to be selected when utilizing a ref in the method call?

Encountering an unfamiliar TS error while working with the code snippet below: <script lang="ts"> import {defineComponent, computed, toRef} from 'vue' import _ from 'lodash' import {DateTime} from 'luxon' int ...

Is there a way to set up gulp without relying on npm when using shared hosting?

While working on my shared hosting, I encountered a roadblock regarding the installation of gulp for compiling LESS assets into CSS. The hosting administrator has declined to install npm, which is essential for setting up gulp. Given this limitation, I am ...

Unraveling the mysteries of webpack configuration

import * as webpack from 'webpack'; ... transforms.webpackConfiguration = (config: webpack.Configuration) => { patchWebpackConfig(config, options); While reviewing code within an Angular project, I came across the snippet above. One part ...

Renaming ngModel in an AngularJS directive's "require" attribute can be achieved by specifying a different alias

I need help with a basic AngularJS directive: <my-directive ng-model="name"></my-directive> I want to change the "ng-model" attribute to "model", but I'm unsure how to pass it to the "require" option in the directive. Here is the full co ...

Using VueJS to iterate through an array while applying a condition to filter out certain elements (combining v-for with v-if)

I'm currently working on a v-for loop to display two columns of card elements. The idea is to print the current element and the next one in a row if the index is even, skipping the elements with odd indexes. This is what my code looks like: <temp ...

Unable to locate the TabBar Review Icon while on the Settings screen

Every time I navigate to the settings screen, the Review Icon (favorite) disappears. However, it reappears when I go back to the Review screen. Can anyone explain why this is happening? Here is a screenshot I captured along with a snippet of code from my p ...

Utilizing npm packages with grunt: A guide

Initially, when I was working with node.js without grunt, I simply had to write the code below to import an external module. var express = require('express'); However, after transitioning to grunt, I attempted to utilize the qr-image module in ...

What is the best way to reposition the caret within an <input type="number"> element?

How can I make the caret move when an input is clicked? The code I found works with text, but not with number. Also, is there a way to pass the length without specifying a value (e.g. 55) in the parameters? HTML <input type="number" name="cost" value= ...

updating the model value in AngularJS2 when the input value is modified

Looking to update a model's value based on user input without relying on the blur event. Unsure of the best approach for this task. Below is the code snippet I have attempted: <div *ngFor='let l of list'> <input #temp [value]= ...

Press a single button to toggle between displaying and hiding the table

$(document).ready(function() { $("#t1").hide(); // hide table by default $('#sp1').on('click', function() { $("#t1").show(); }); $('#close').on('click', function() { $("#t1").hide(); }); }); <li ...

PayPal Integration with React for Seamless Checkout Experience

I established a small and uncomplicated online store featuring a PayPal checkout system, and it is functioning adequately. Now, I am looking to include detailed information about the purchased products in the transaction history of my PayPal account. This ...

Prevent vertical axis rotation in OrbitControls with THREE.js

In my three.js project, I have a scene with OrbitControls that allows me to rotate the camera around the origin at position 0,0,0. I am attempting to restrict the camera rotation to only rotate vertically along the y-axis infinitely (up or down). You can ...

Am I on the right track in my understanding of how document and viewport relate to mouse position in JavaScript?

After reviewing responses from a previous inquiry, it is evident that both pertain to the x and y coordinates of mouse positions. In relation to the document and In relation to the viewport. I have delved into an article on QuirksMode, yet I feel ther ...