AngularJS - bind to directive resize

后端 未结 6 1835
Happy的楠姐
Happy的楠姐 2020-12-08 20:18

How can i be notified when a directive is resized? i have tried

element[0].onresize = function() {
            console.log(element[0].offsetWidth + \" \" +          


        
6条回答
  •  借酒劲吻你
    2020-12-08 20:58

    The only way you would be able to detect size/position changes on an element using $watch is if you constantly updated your scope using something like $interval or $timeout. While possible, it can become an expensive operation, and really slow your app down.

    One way you could detect a change on an element is by calling requestAnimationFrame.

    var previousPosition = element[0].getBoundingClientRect();
    
    onFrame();
    
    function onFrame() {
      var currentPosition = element[0].getBoundingClientRect();
    
      if (!angular.equals(previousPosition, currentPosition)) {
        resiszeNotifier();
      }
    
      previousPosition = currentPosition;
      requestAnimationFrame(onFrame);
    }
    
    function resiszeNotifier() {
      // Notify...
    }
    

    Here's a Plunk demonstrating this. As long as you're moving the box around, it will stay red.

    http://plnkr.co/edit/qiMJaeipE9DgFsYd0sfr?p=preview

提交回复
热议问题