0

I have created a custom directive in AngularJS. The code is as follows:

var esscom = angular.module('esscom',['ngMaterial' ,'ngMessages','ui.bootstrap','ui.router']);


esscom.directive('resize',[function($window){
    return function($scope){
        console.log("Inside resize dir");
        angular.element($window).bind('resize', function() {
            console.log("Window resize");
            if( $window.innerWidth <= 960){
                console.log("Returning ess background");
                angular.element("#view").addClass('essbackground');
            }
            $scope.$apply();
        })
    };
}]);

The HTML is as follows:

<div resize id="view">
    <h1>Resize this</h1>
</div>

This just doesn't work. The resize event is never detected. Am I doing anything wrong?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Sohan Shirodkar
  • 510
  • 3
  • 24

1 Answers1

0

The directive function should return like the following:

esscom.directive('resize',['$window',function($window){
    return {
        link:function($scope){
            console.log("Inside resize dir");
            angular.element($window).bind('resize', function() {
                console.log("Window resize");
                if( $window.innerWidth <= 960){
                    console.log("Returning ess background");
                    angular.element("#view").addClass('essbackground');
                }
                $scope.$apply();
            })
        }
    };
}]);

You need to inject $window.

Shawn
  • 2,675
  • 3
  • 25
  • 48
  • I referred this question : http://stackoverflow.com/questions/23044338/window-resize-directive. This made me construct the directive the way I have typed in the question, although I know it should return an object. But your syntax also doesn't work. I have tried it. – Sohan Shirodkar Oct 05 '16 at 17:13
  • If I am not wrong, the `resize` event will be triggered by browser window resize – Sohan Shirodkar Oct 05 '16 at 17:14
  • 1
    Oh you forgot to inject `$window`. See my updated answer. – Shawn Oct 05 '16 at 17:16