title: How can I get the window width in angularJS on resize from a controller?
body: <p>Ho can I get the window width in angularJS on resize from a controller?  I want to be able to get it so I can display some <code>div</code> with <code>&lt;div ng-if="windowWidth &gt; 320"&gt;</code></p>
  
  <p>I can get the windowWidth on the initial page load but not on resize...</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>'use strict';
  
  var app = angular.module('app', []);
  
  app.controller('mainController', ['$window', '$scope', function($window, $scope){
   var mainCtrl = this;
   mainCtrl.test = 'testing mainController';
    
      // Method suggested in @Baconbeastnz's answer  
      $(window).resize(function() {
        $scope.$apply(function() {
          $scope.windowWidth = $( window ).width();
        });
      });
    
      /* this produces the following error
      /* Uncaught TypeError: mainCtrl.$digest is not a function(…)
      angular.element($window).bind('resize', function(){
          mainCtrl.windowWidth  = $window.innerWidth;
          // manuall $digest required as resize event
          // is outside of angular
          mainCtrl.$digest();
      });  
      */
  }]);
  
  // Trying Directive method as suggested in @Yaser Adel Mehraban answer.
  /*app.directive('myDirective', ['$window', function ($window) {
       return {
          link: link,
          restrict: 'E'            
       };
       function link(scope, element, attrs){
         angular.element($window).bind('resize', function(){
             scope.windowWidth = $window.innerWidth;
         });    
       }    
   }]);*/</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"&gt;&lt;/script&gt;
  &lt;script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.9/angular.min.js"&gt;&lt;/script&gt;
  &lt;body ng-app="app" ng-controller="mainController as mainCtrl"&gt;
   &lt;p&gt;{{mainCtrl.test}}&lt;/p&gt;
   &lt;hr /&gt;
      &lt;p ng-if="windowWidth &gt; 600"&gt;The window width is {{windowWidth}}&lt;/p&gt;
      &lt;div my-directive ng-if="windowWidth &gt; 320"&gt;It works!&lt;/div&gt;
  &lt;/body&gt;</code></pre>
  </div>
  </div>
  </p>
  
  <p>I see in <a href="https://stackoverflow.com/a/31623803/1814446">this answer</a> they explain how you can get it from within a directive but how can you get it to work from within a controller?</p>