I'm looking for a way to watch changes on window inner width size change. I tried the following and it didn't work:
$scope.$watch('window.innerWidth', function() {
console.log(window.innerWidth);
});
any suggestions?
This question is related to
javascript
jquery
angularjs
angularjs-scope
If Khanh TO's solution caused UI issues for you (like it did for me) try using $timeout
to not update the attribute until it has been unchanged for 500ms.
var oldWidth = window.innerWidth;
$(window).on('resize.doResize', function () {
var newWidth = window.innerWidth,
updateStuffTimer;
if (newWidth !== oldWidth) {
$timeout.cancel(updateStuffTimer);
}
updateStuffTimer = $timeout(function() {
updateStuff(newWidth); // Update the attribute based on window.innerWidth
}, 500);
});
$scope.$on('$destroy',function (){
$(window).off('resize.doResize'); // remove the handler added earlier
});
Reference: https://gist.github.com/tommaitland/7579618
No need for jQuery! This simple snippet works fine for me. It uses angular.element() to bind window resize event.
/**
* Window resize event handling
*/
angular.element($window).on('resize', function () {
console.log($window.innerWidth);
});
/**
* Window resize unbind event
*/
angular.element($window).off('resize');
I found a jfiddle that might help here: http://jsfiddle.net/jaredwilli/SfJ8c/
Ive refactored the code to make it simpler for this.
// In your controller
var w = angular.element($window);
$scope.$watch(
function () {
return $window.innerWidth;
},
function (value) {
$scope.windowWidth = value;
},
true
);
w.bind('resize', function(){
$scope.$apply();
});
You can then reference to windowWidth from the html
<span ng-bind="windowWidth"></span>
Source: Stackoverflow.com