[英]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.