Kevin Kevin - 1 year ago 167
Javascript Question

How can I trigger resize event in AngularJS

I'm using Angular & Bootstrap, with the nav tab control to switch visibility of divs. In one div, I have a large img (CAD drawing of building). I also then overlay markers on the image. I want to scale the x/y position of the markers based on the image width & image naturalWidth. I'm using a resize directive to detect changes and update my scope.

My problem is that if user switches tabs and switches back to the div with the CAD img, the refresh doesn't happen until I resize the browser (or surprisingly if I press the CMD key on Mac).

Is there an angular way to trigger the resize event to force my markers to be recalculated. Or is there an event I can tap into that is fired when the is fully displayed ?

Or is there a more refined angular approach I should take?

This is the HTML, the resize directive I've written is on the tag.

<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 />

And this is the resize directive (adapted from

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;
scope.imgScale = 1;
console.log("watched resize event - scale = "+scope.imgScale)
}, true);
w.bind('resize', function() {
console.log("'resize' - scale = "+scope.imgScale)

Answer Source

Try injecting $timeout into the resize directive:

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

... then add the following line to the bottom of it:

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

This should trigger the handler you have bound to $window.resize just after the browser renders.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download