How to detect the orientation change

In IONIC i need to check the orientation change in android and ios. how to detect it ?

Check out the ngCordova plugin to detect device orientation http://ngcordova.com/docs/plugins/deviceOrientation/

1 Like

Is it possible to prevent the orientation change in ionic code itself. Normally we will do the orientation fix in android xml file instead i have to handle it in my code. Any possible way to handle ?

1 Like

yes in config.xml add

<preference name="Orientation" value="portrait"/>
1 Like

can u provide me the clearly. do we need to create xml file for this in ionic to use ?. I am just new to ionic so your example will helpful to proceed further

What I was saying, was adding in the orientation plugin and accesing it through your javascript. Read the plugin docs on how to use the API, but I’m not sure I know what you mean by the “ionic code”, I’m assuming you are talking about your angular code which uses ionic specific capabilities.

Hi guys i need to detect device orientation but i would like use my app only in portratit mode. in config XML i set portrait and now i must instance $cordovaDeviceOrientation.
Can i instance in app.run ? o i must instance one by one in my controller?
i’m tring to instance it but i can’t do

1 Like

To detect screen orientation:

  function doOnOrientationChange()
  {
    switch(window.orientation) 
    {  
      case -90:
      case 90:
        alert('landscape');
        break; 
      default:
        alert('portrait');
        break; 
    }
  }

  window.addEventListener('orientationchange', doOnOrientationChange);

You can lock screen orientation using this plugin:net.yoik.cordova.plugins.screenorientation

Read more about it here: Gajotres - Best Technology Product Reviews, News, Tips, and Comparison

3 Likes

@Gajotres answer did not work for me. I don’t know exactly why elements had zero height/width inside doOnOrientationChange

End up doing this:

angular.element(window).on('resize', windowResizeHandler);
function windowResizeHandler( ) {
                        var w = element.prop('offsetWidth');
                        var h = attrs.heightMultiplier * w;
                        if (w && h) {
                            element.css('height', h + 'px');
                        } else {
                            console.log('height NOT set');
                        }
                    }
1 Like

@yurinondual I have added the code into config.xml

 <preference name="Orientation" value="landscape"/>

but it still view in portrait, then I open the config.xml file again, the code is gone. :anguished: