如何在页面中进行指令更新被滚动或调整大小

时间:2014-03-20 07:33:57

标签: javascript angularjs-directive

我有一个指令,它将两个类设置为一个元素,以识别它在浏览器窗口中的哪个象限(左上角,右上角,左下角,右下角)。代码与此类似:

angular.module('positionerDirective', [])
  .directive('positioner', function() {
    return {
      restrict: 'A',
      link: function(scope, element){
        var top = element[0].offsetTop;
        var left = element[0].offsetLeft;
        //do whatever math you need here
        angular.element(element).addClass(class you need);
      }
    };
  });

我遇到的问题是,如果用户滚动或更改屏幕大小,象限可能会发生变化,如果发生这种情况,我需要更新类。所以我的问题是,如果左/顶部发生变化,如何让指令再次运行?

1 个答案:

答案 0 :(得分:1)

您可以将控制器添加到您的指令,在其中订阅resizescroll的DOM事件并相应地更新类。这是一个这样做的例子:

<强>的JavaScript

angular.module('positionerDirective', []).
  directive('positioner', function() {
    return {
      restrict: 'A',
      scope: true, // <- create isolated scope
      link: function(scope, element) {
        var el = element[0];
        scope.$watch(function() {
          return (el.offsetTop - scope.scrollTop)+':'+(el.offsetLeft - scope.scrollLeft); // <- check element class is to be updated
        }, function() {
          el.className = 'top-'+(el.offsetTop - scope.scrollTop)+' left-'+(el.offsetLeft - scope.scrollLeft); // <- apply new element class
        });
      },
      controller: ['$scope', '$window', function($scope, $window) {
        $scope.updatePosition = function() {
          $scope.scrollTop = $window.document.body.scrollTop,
          $scope.scrollLeft = $window.document.body.scrollLeft;
          if ($scope.$root.$$phase != '$apply' && $scope.$root.$$phase != '$digest') { // <- Avoid call of $apply while digest is already running
            $scope.$apply();
          }
        }
        angular.element($window).on('resize scroll', function() { // <- subscribe to DOM events and update scope accordingly
          $scope.updatePosition();
        });
        $scope.updatePosition(); // <- set initial values of $scope.scrollTop and $scope.scrollLeft
      }]
    };
  });

Plunker:http://plnkr.co/edit/wvYTZ18gY2N5ABODyZO7?p=preview