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);

3 Answers 3

32
angular.element($window).bind('orientationchange', function () {

});
4
  • 1
    Thx, easier than I thought!
    – tdhulster
    Jun 6, 2014 at 11:02
  • 3
    Ofc don't forget to inject $window in your controller !
    – amdev
    Oct 3, 2016 at 9:06
  • 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.
    – amdev
    Oct 3, 2016 at 9:37
  • Don't forget to add $scope.$apply();
    – Weihui Guo
    Sep 13, 2017 at 18:13
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});
            });

        }
    };
}]);
1
  • This solution helped me in my map directive. Thx =D Jul 2, 2015 at 14:44
4

I implemented it this way:

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

What do you think?

Comments are welcome.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.