1

I tried to implement a window resize custom directive and it works fine.

The problem is it works only if i use the directive name as resize. Otherwise if i use different name as windowsize,it is triggered only at the time of page refresh.

here is the controller code

  var app = angular.module('miniapp', []);

function AppController($scope) {
    /* Logic goes here */
}

> > app.directive('windowsize', function($window){
>         return function(scope,element){
>             var w=angular.element($window);
>             scope.getWindowDimension=function(){
>                 return{
>                      'w': w.width()
>                 };
>             };
>              scope.$watch(scope.getWindowDimension, function (newValue, oldValue) {
>              scope.windowWidth = newValue.w;
>              console.log( scope.windowWidth);
> 
>         }, true);
>               w.bind('windowsize', function () {
>             scope.$apply();
>         });
>        };
>      })



html code
<div ng-app="miniapp" ng-controller="AppController"  windowsize>
    window.height: {{windowHeight}}
    <br />window.width: {{windowWidth}}
    <br />
</div>
Mangu Singh Rajpurohit
  • 10,806
  • 4
  • 68
  • 97
Sanjay Hp
  • 169
  • 3
  • 11

1 Answers1

0

var app = angular.module('miniapp', []);

function AppController($scope) {
    /* Logic goes here */
}

 app.directive('windowsize', function($window){
         return function(scope,element){
             var w=angular.element($window);
             scope.getWindowDimension=function(){
                 return{
                      'w': w.width()
                 };
             };
              scope.$watch(scope.getWindowDimension, function (newValue, oldValue) {
              scope.windowWidth = newValue.w;
              console.log( scope.windowWidth); 
         }, true);
               w.bind('resize', function () {
             scope.$apply();
         });
        };
      })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
html code
<div ng-app="miniapp" ng-controller="AppController"  windowsize>
    window.height: {{windowHeight}}
    <br />window.width: {{windowWidth}}
    <br />
</div>

Here In this example you done everything correct but one small mistake, you bind event windowresize is not event so use resize and try it(I just correct for width only)

Ronak
  • 36
  • 5