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 div
with <div ng-if="windowWidth > 320">
I can get the windowWidth on the initial page load but not on resize...
'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;
});
}
}]);*/
<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 ng-app="app" ng-controller="mainController as mainCtrl">
<p>{{mainCtrl.test}}</p>
<hr />
<p ng-if="windowWidth > 600">The window width is {{windowWidth}}</p>
<div my-directive ng-if="windowWidth > 320">It works!</div>
</body>
I see in this answer they explain how you can get it from within a directive but how can you get it to work from within a controller?