2

I have a page that renders table view or div/blocks view depending on window width. But the swop between views happens very slow. Maybe I am not doing things in the best way?

I basically have 2 scope variables(block and table, set to true or false) defined in the controller.

I have a directive that is triggered on window resize and according to this width I will set the controller scope variables to true or false.

The template renders table or divs according to the ng-if condition of the scope variables.

template:

<div view-controll 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('viewControll', ['$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();
            })
        }
    }
}]);

2 Answers 2

5

The slowness you're experiencing could be due to the fact that after the window has been resized, a digest cycle isn't triggered. The fact that the view changes at all I suspect is due to the fact the digest cycle is later triggered by something else.

To fix this, you can call scope.$apply() inside the resize handler:

angular.element($window).bind('resize', function() {
  scope.resize();
  scope.$apply();
});
Sign up to request clarification or add additional context in comments.

Comments

0

You should use $evalAsync.

Avoid using $apply because it invokes the $digest cycle and execute the entire list of watchers of all available scope in the application, which can cause performance issues.

Example:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.