Improve slow angular directive

时间:2015-06-22 11:01:27

标签: javascript angularjs angularjs-directive

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 个答案:

答案 0 :(得分:5)

您遇到的缓慢可能是因为在调整窗口大小后,不会触发摘要周期。事实上我认为视图发生了变化,这是因为摘要周期后来被其他事件触发了。

要解决此问题,您可以在调整大小处理程序中调用angular.element($window).bind('resize', function() { scope.resize(); scope.$apply(); });

{{1}}

答案 1 :(得分:0)

您应该使用$evalAsync

避免使用$apply,因为它会调用$ digest循环并执行应用程序中所有可用范围的观察者列表,这可能会导致性能问题。

示例:

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