AngularJS $watch window resize inside directive

Lightfooted picture Lightfooted · Jul 25, 2015 · Viewed 101.4k times · Source

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

Answer

Matt Herbstritt picture Matt Herbstritt · Jul 25, 2015

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

     }

 }]);