簡體   English   中英

如何在AngularJS中觸發resize事件

[英]How can I trigger resize event in AngularJS

我正在使用Angular和Bootstrap,使用nav選項卡控件來切換div的可見性。 在一個div中,我有一個大的img(建築物的CAD繪圖)。 然后我還在圖像上疊加標記。 我想根據圖像寬度和圖像naturalWidth縮放標記的x / y位置。 我正在使用resize指令來檢測更改並更新我的范圍。

我的問題是,如果用戶使用CAD img切換標簽並切換回div,則在我調整瀏覽器大小之前不會進行刷新(或者如果我按下Mac上的CMD鍵,則會令人驚訝)。

是否有角度方式觸發resize事件以強制重新計算我的標記。 或者是否有一個我可以點擊的事件在完全顯示時會被觸發?

或者我應該采取更精確的角度方法?

這是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();
    });
  };
}).

當上述情況沒有時,這對我有用。

$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

嘗試在resize指令中注入$timeout

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

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

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

這應該在瀏覽器渲染之后觸發綁定到$window.resize的處理程序。

接受的答案對我不起作用 - w未定義。

這樣做:

$timeout(function(){
    $(window).trigger('resize');
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM