简体   繁体   中英

How to detect mobile device

I am building a mobile site using the ionic framework. I want to detect mobile devices(Android and iOS) with AngularJS (or ionic).

If access device is Android → #/android if access device is iOS → #/ios

controllers.js

function uaCtrl('$scope', '$location', ($scope, $location) {
$scope = function () {
  var isMobile = {
    Android: function() {
      return navigator.userAgent.match(/Android/i);
    },
    iOS: function() {
      return navigator.userAgent.match(/iPhone | iPad | iPod/i)
    }
  }

  if(isMobile.Android()) {
    $location.path('#/android');
  }else if(isMobile.iOS()) {
    $location.path('#/ios');
  }else{
    $location.path('#/ios');
  }

};

};

app.js

.config(function($stateProvider, $urlRouterProvider) {
  $urlRouterProvider.otherwise('/dash');

  $stateProvider

  .state('home', {
      url: '/dash',
      templateUrl: 'templates/dash.html'
    })

  .state('android-home', {
    url: '/android',
    templateUrl:'templates/dash-android.html'
  })

  .state('ios-home', {
    url: '/ios',
    templateUrl:'templates/dash-ios.html'
  })
});

dash.html

<ion-view hide-nav-bar="true" ng-controller="uaCtrl">
    ?????
</ion-view>

ionic.Platform.isIOS() I believe is what you're looking for.

Platform docs: http://ionicframework.com/docs/api/utility/ionic.Platform/

It's unit tests: https://github.com/driftyco/ionic/blob/master/test/unit/angular/service/platform.unit.js

However, I wouldn't recommend using different markup structures if you don't have to. Instead, if you have different styles depending on the platform, Ionic places platform-android or platform-ios in the body tag class, so you could do things like:

.platform-android h1 { color: green; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM