Search code examples
angularjsresizewindowdirectivewatch

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... @_@;


Solution

  • 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();
           });
    
         }
    
     }]);