app.directive('resize', function($window) {
return {
link: function(scope) {
function onResize(e) {
// Namespacing events with name of directive + event to avoid collisions
scope.$broadcast('resize::resize');
}
function cleanUp() {
angular.element($window).off('resize', onResize);
}
angular.element($window).on('resize', onResize);
scope.$on('$destroy', cleanUp);
}
}
});
Which can be used, in the basic case, on the root element of the app
<body ng-app="myApp" resize>...
And then listen for the event in other directives
<div my-directive>
coded up as:
app.directive('myDirective', function() {
return {
link: function(scope, element) {
scope.$on('resize::resize', function() {
doSomethingFancy(element);
});
});
}
});
You can extend the directive with options, and use it differently in different parts of your app. Say you want different debounced versions in different parts:
link: function(scope, element, attrs) {
var wait = 0;
attrs.$observe('resize', function(newWait) {
wait = $window.parseInt(newWait || 0);
});
angular.element($window).on('resize', $window._.debounce(function() {
scope.$broadcast('resize::resize');
}, wait));
}
Used as:
<div resize>
<!-- Undebounced 'resize' Angular events here -->
</div>
<div resize="500">
<!-- 'resize' is debounced by 500 milliseconds -->
</div>
You can later extend the directive with other events that might be useful. Maybe things like resize::heightIncrease. resize::heightDecrease, resize::widthIncrease, resize::widthDecrease. You then have one place in your app that deals with remembering and processing the exact dimensions of the window.
You can pass data along with the events. Say like the viewport height/width where you might need to deal with cross-browser issues (depending on how far back you need IE support, and whether you include another library to help...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.