Window orientationchange event in Angular
Asked Answered
B

3

12

Is there a way to call the orientationchange event inside an AngularJS directive?

I'm currently working with angular-masonry and I'm trying to update/refresh masonry when the orientation of the mobile device changes.

I've found this but I'm wondering how to do this with the $window service inside Angular

window.addEventListener("orientationchange", function() {
  // Announce the new orientation number
  console.log(window.orientation);
}, false);
Breakdown answered 10/4, 2014 at 14:49 Comment(0)
N
32
angular.element($window).bind('orientationchange', function () {

});
Nought answered 6/6, 2014 at 10:57 Comment(4)
Thx, easier than I thought!Breakdown
Ofc don't forget to inject $window in your controller !Tananarive
But there is something very strange, 'orientationchange" is fire before the screen width change ... So if I execute something just after 'orientationchange' and try to get the new width it doesn't work, give me the old one.Tananarive
Don't forget to add $scope.$apply();Jessy
R
6

Hope this helps. Attach directive as attr, to body. Tested with IPhone 5.

'use strict';

angular.module('appModuleNameHere')
    .directive('DirPrefixNameOrientationChange', ['$rootScope',function ($state) {
    return {
        restrict: 'A',
        replace: true,
        link: function postLink($scope, element, attrs) {

            element.bind('orientationchange', function () {
                $state.go($state.current, {}, {reload: true});
            });

        }
    };
}]);
Righthanded answered 19/2, 2015 at 0:48 Comment(1)
This solution helped me in my map directive. Thx =DElkeelkhound
D
4

I implemented it this way:

$window.addEventListener('orientationchange', function() {
  your code here
}, false);

What do you think?

Comments are welcome.

Deirdra answered 30/1, 2015 at 12:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.