How can I get the window width in angularJS on resize from a controller?

The best way is to use a directive and watch for resize event of the window:

'use strict';

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

app.directive('myDirective', ['$window', function ($window) {

     return {
        link: link,
        restrict: 'A'           
     };

     function link(scope, element, attrs){

       angular.element($window).bind('resize', function(){
           scope.windowWidth = $window.innerWidth;
       });    
     }    
 }]);

And use it on your div:

<div my-directive ng-if="windowWidth > 320">

Here is a working plunker.


Finnally got it working with the below. Took most of the code from https://stackoverflow.com/a/23078185/1814446.

The only difference was for the ng-if to work the directive had to be put on a parent html element.

'use strict';

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

app.controller('mainController', ['$window', '$scope', function($window, $scope){
	var mainCtrl = this;
	mainCtrl.test = 'testing mainController';
}]);

app.directive('windowSize', function ($window) {
  return function (scope, element) {
    var w = angular.element($window);
    scope.getWindowDimensions = function () {
        return {
            'h': w.height(),
            'w': w.width()
        };
    };
    scope.$watch(scope.getWindowDimensions, function (newValue, oldValue) {
      scope.windowHeight = newValue.h;
      scope.windowWidth = newValue.w;
      scope.style = function () {
          return {
              'height': (newValue.h - 100) + 'px',
              'width': (newValue.w - 100) + 'px'
          };
      };
    }, true);

    w.bind('resize', function () {
        scope.$apply();
    });
  }
})
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.9/angular.min.js"></script>
<body window-size my-directive ng-app="app" ng-controller="mainController as mainCtrl">
  <p>{{mainCtrl.test}}</p>
  <hr />
  <div ng-if="windowWidth > 500">
    <h4 style="margin:5px 0">It works!</h4>
    <p style="margin:0">window.height: {{windowHeight}}</p>			     <p style="margin:0">window.width: {{windowWidth}}</p>			     <p style="margin:0">{{mainCtrl.test}}</p>
  </div>
</body>

Tags:

Angularjs