Enhance the efficiency of a sluggish angular directive

I am facing an issue with the speed at which my page switches between table view and div/block view based on window width. I suspect there might be a more efficient way to handle this process?

In my controller, I have defined two scope variables (block and table) that are set to true or false.

There is a directive triggered by window resize events that updates these scope variables based on the window width.

The template renders either a table or divs depending on the ng-if condition of the scope variables.

Template:

<div view-control ng-controller="viewController">

  <div ng-if="table==true" id="tableView">
    <div class="table-responsive">
      <table class="table table-striped table-condensed">
         <tbody>
          <tr class="tableRowsDocs" ng-repeat="dbo in rows">
            //data
          </tr>
        </tbody>
      </table>
    </div>
  </div>

  <div ng-if="block==true" id="mobileView">
    <div class="col-xs-12 col-sm-6 col-md-3" ng-repeat="dbo in rows">
     //data
    </div>
  </div>

</div>

Controller:

 app.controller('viewController', function($scope) {
      $scope.block = false;
      $scope.table = true;
    });

Directive:

app.directive('viewControl', ['$window', function($window) {
    return {
        link: function(scope, elem, attrs) {
            scope.onResize = function() {               
                if (window.innerWidth > 700){
                  scope.block = false;
                  scope.table = true;
                } else{
                  scope.block = true;
                  scope.table = false;
                }
            }
            scope.onResize();
            angular.element($window).bind('resize', function() {
                scope.onResize();
            })
        }
    }
}]);

Answer №1

If you're noticing a delay in performance, it could be because the digest cycle is not being triggered after window resizing. The change in view may only occur when something else triggers the digest cycle later on.

To address this issue, consider adding scope.$apply() within the resize handler:

angular.element($window).bind('resize', function() {
  scope.resize();
  scope.$apply();
});

Answer №2

It is recommended to utilize $evalAsync.

It's best to steer clear of using $apply as it triggers the $digest cycle and processes all watch functions within every scope in the application, potentially leading to performance problems.

Here's an example:

scope.$evalAsync(function() {
  scope.adjustSize();
});

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

What is the best method for typing a component prop that is compatible with singular use and can also function within loops without disrupting intellisense?

The Scenario Within a heading component, I have defined various types as shown below: // Heading/index.d.ts import { HTMLAttributes } from 'react'; export const HeadingType: { product: 'product'; marketing: 'marketing'; ...

Combine the results of callbacks executed in a loop and return the final concatenated value

I have a dilemma with my data stored in MongoDB. I am currently attempting to update the score whenever it is triggered. However, due to the nature of my task, I find myself needing to execute multiple queries depending on a loop. Ultimately, my goal is t ...

A guide on displaying an array object in a table column using Vue.js and Element UI

Having issues with rendering array data in Vue Js Element UI using the el-table-column element. The string data displays correctly, but I'm facing problems with the array data. I've attempted to include static data within the data() return method ...

The value within the style.setProperty function does not get applied

I have a progress bar that dynamically increases based on user input: <div class="progressBarContainer percentBar"> <div class="progressBarPercent" style="--width:${gPercent}" id="${gName}-pbar">< ...

Adjust the height of a CSS div to automatically fit the space between two other divs

I am trying to adjust the height of my table (with class "body") so it automatically fits the remaining space between the header div and the footer div. All three divs are enclosed within a fixed and centered position on the screen. Update: JSFiddle w ...

Issues with basic emit and listener in socket.io

I recently inherited an App that already has socket IO functioning for various events. The App is a game where pieces are moved on a board and moves are recorded using notation. My task is to work on the notation feature. However, I am facing issues while ...

Looking to grasp the concept of calling inline functions within a React functional component

As a newcomer to React, I recently created a new view within my company. Following the example of many guides, I have utilized inline functions and function components exclusively. One common practice I have adopted is writing onClick events in this manne ...

Just got Expo up and running for the first time, encountered an error right after setting it up

After diligently following the steps outlined on https://facebook.github.io/react-native/docs/getting-started I proceeded with a fresh npm installation and executed the npm update command Subsequently, I entered the command npm install -g expo-cli Altho ...

jQuery's remove/add class functionality seems to only function once

I haven't had much sleep and I'm not sure if toggleClass will work for this situation. Here is the code I currently have: $(document).ready(function() { // Slide Mobile Filter Sidebar Onto Screen $('#showFilters').on('clic ...

Why is it that when I click outside of the <html> element, the click event bound to the <html> element is triggered?

const html = document.querySelector('html') const body = document.querySelector('body') body.onclick = () => { console.log('body clicked') } html.onclick = () => { console.log('html clicked') } document. ...

Drawing on Canvas with Html5, shifting canvas results in significant issues

I've been working on developing an HTML5 drawing app, and while I have all the functionality sorted out, I'm facing challenges during the design phase. My main issue is centered around trying to make everything look visually appealing. Specifical ...

How can I pass arguments from a Python command line program (compiled to an EXE) to a JavaScript file?

As I work on developing a node program, I've come across certain abilities that Python possesses which JavaScript lacks, such as utilizing Python-specific modules. To bridge this gap, I made the decision to compile Python files into EXE and then invok ...

Unable to pass props to component data using Vue framework

I'm facing an issue with passing props in my component to the same component's data object. For some reason, I'm only receiving null values. Does anyone have any suggestions on how I should approach this problem? It seems like my Vue compone ...

What are the implications of incorporating listeners in redux action creators?

While developing my app, I have a feature that involves constantly monitoring location changes and updating the store accordingly. One question that has arisen is whether it would be beneficial to keep the listeners inside the action creator rather than th ...

ReactJs allows for fluid scroll animations that persist as long as the mouse is clicked or a button

Just some background information: I'm aiming to replicate the scrolling effect seen in Etsy's product image thumbnails carousel. Essentially, when you hover over the top part of the div, it automatically scrolls down until the last image is reve ...

Suggestions for displaying images of varying resolutions in a circular format similar to Google's style

What is the best way to display dynamic images with varying resolutions in a circle like Google? I have tried using the Bootstrap class "img-circle", but it only works for images with a resolution of 304*236. If the image resolution is different, it appear ...

Enhance $ by incorporating additional functionalities using jQuery

Seeking some assistance on how to properly implement the syntax $.functionName(args) I've made attempts using jQuery.extend and $.fn: $.fn.alertSometing = function(param) { alert(param); }; However, upon running: $('.button').on(' ...

Is there a browser that enables me to methodically go through network requests individually?

I am currently seeking a way to identify which network requests on my webpage are causing an issue. (Alternatively, I am looking for a method to remotely guide someone through this process.) Are there any browsers that provide the ability to "step through ...

How can we retrieve window.top in JavaScript when accessing it through window.opener?

In the scenario of my popup window, I am attempting to make reference to window.top using this link: My goal is to access the main window's document from the popup, however when I use window.top, it returns undefined. ...

What is the best way to navigate a static dual navigation bar?

I'm currently working with two fixed and responsive navbars. Below is the code I'm using: function myFunction() { var x = document.getElementById("myTopnav"); if (x.className === "topnav") { x.className += " responsive"; } else { ...