Skip to content

Instantly share code, notes, and snippets.

@robertu7
Forked from mlynch/autofocus.js
Last active August 29, 2015 14:16
Show Gist options
  • Save robertu7/4f8bec8e2d8eb2433267 to your computer and use it in GitHub Desktop.
Save robertu7/4f8bec8e2d8eb2433267 to your computer and use it in GitHub Desktop.
AngularJS Directive:Autofocus 基於是否為 Mobile Browser
/**
* the HTML5 autofocus property can be finicky when it comes to dynamically loaded
* templates and such with AngularJS. Use this simple directive to
* tame this beast once and for all.
*
* Usage:
* <input type="text" autofocus>
*/
angular.module('autofocusDirective', [])
.directive('autofocus', ['$rootScope', '$window', '$timeout', function ($rootScope, $window, $timeout){
return {
restrict: 'A',
controller: function (){
// 檢測是否為手機瀏覽器
// https://stackoverflow.com/questions/11381673/detecting-a-mobile-browser
function detectmob() {
var ua = $window.navigator.userAgent;
if(
ua.match(/Android/i)
|| ua.match(/webOS/i)
|| ua.match(/iPhone/i)
|| ua.match(/iPad/i)
|| ua.match(/iPod/i)
|| ua.match(/BlackBerry/i)
|| ua.match(/Windows Phone/i)
){
return true;
}
else {
return false;
}
}
$rootScope.isMobile = detectmob()
},
link: function (scope, elem){
if (!$rootScope.isMobile){
$timeout(function (){
elem[0].focus()
})
} else {
// do something
}
}
}
}])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment