Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS $watch window resize inside directive

I have revealing module pattern which looks like this:

'use strict';  angular.module('app', [])    .directive('myDirective', ['SomeDep', function (SomeDep) {        var linker = function (scope, element, attr) {           // some work        };         return {           link: linker,           restrict: 'E'        };    }]) ; 

What I'm having trouble with is integrating a $watch into this. Specifically watching for window resize, with the '$window' service.

[EDIT]:

I realised what my issue was this whole time... I was restricting to element, when I forgot that I was implementing it as an attribute... @_@;

like image 682
Lightfooted Avatar asked Jul 25 '15 03:07

Lightfooted


1 Answers

You shouldn't need a $watch. Just bind to resize event on window:

DEMO

'use strict';  var app = angular.module('plunker', []);  app.directive('myDirective', ['$window', function ($window) {       return {         link: link,         restrict: 'E',         template: '<div>window size: {{width}}px</div>'      };       function link(scope, element, attrs){         scope.width = $window.innerWidth;         angular.element($window).bind('resize', function(){           scope.width = $window.innerWidth;           // manuall $digest required as resize event          // is outside of angular          scope.$digest();        });       }   }]); 
like image 54
Matt Herbstritt Avatar answered Oct 10 '22 17:10

Matt Herbstritt