How to device detector use AngularJS

2019-06-13 02:44发布

问题:

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>

回答1:

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