如何在AngularJS中触发resize事件

时间:2014-05-13 17:23:52

标签: javascript angularjs

我正在使用Angular& Bootstrap,使用nav选项卡控件切换div的可见性。在一个div中,我有一个大的img(建筑物的CAD绘图)。然后我还在图像上叠加标记。我想根据图像宽度和宽度来缩放标记的x / y位置。 image naturalWidth。我正在使用resize指令来检测更改并更新我的范围。

我的问题是,如果用户使用CAD img切换标签并切换回div,则在我调整浏览器大小之前不会进行刷新(或者如果我按下Mac上的CMD键,则会令人惊讶)。

是否有一种角度方式来触发调整大小事件以强制重新计算我的标记。或者是否有一个我可以点击的事件在完全显示时会被触发?

或者我应该采取更精确的角度方法吗?

这是HTML,我写的resize指令在标签上。

<div id="imageDiv" style="position: relative;"  ng-show="selectedLocation"  >
  <img ng-src="../maps/image/{{selectedLocation}}" 
       style=" max-width: 100%; max-height: auto; border:solid 1px black" resize  imageonload />
</div>

这是resize指令(改编自http://jsfiddle.net/jaredwilli/SfJ8c/

directive('resize', function($window) {
  return function(scope, element) {
    var w = angular.element($window);

    scope.imgCadImage = element;

    scope.getWindowDimensions = function() {
      return {
        'h' : scope.imgCadImage[0].width,
        'w' : scope.imgCadImage[0].height
      };
    };
    scope.$watch(scope.getWindowDimensions, function(newValue, oldValue) {
      if (scope.imgCadImage[0].naturalWidth)
        scope.imgScale = newValue.w / scope.imgCadImage[0].naturalWidth;
      else
        scope.imgScale = 1;
      console.log("watched resize event - scale = "+scope.imgScale)
      scope.updateCADMarkersAfterResize();
    }, true);
    w.bind('resize', function() {
      console.log("'resize' - scale = "+scope.imgScale)
      scope.$apply();
    });
  };
}).

3 个答案:

答案 0 :(得分:15)

当上述情况没有时,这对我有用。

$timeout(function() {
    $window.dispatchEvent(new Event("resize"));
}, 100);

我还必须使用$timeout延迟我的情况,以防止有关正在进行的摘要周期的错误。并非所有用例都需要这样。

dispatchEvent得到了很好的支持http://caniuse.com/#feat=dispatchevent

但是,你需要IE9和IE10支持你必须使用他们的propritary方法:https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/fireEvent

答案 1 :(得分:10)

尝试将$timeout注入resize指令:

directive('resize', function($window, $timeout) {

...然后在其底部添加以下行:

$timeout(function(){ w.triggerHandler('resize') });

这应该在浏览器渲染后触发您绑定到$window.resize的处理程序。

答案 2 :(得分:2)

接受的答案对我不起作用 - w未定义。

这样做了:

$timeout(function(){
    $(window).trigger('resize');
});
相关问题