-
-
Save robertu7/4f8bec8e2d8eb2433267 to your computer and use it in GitHub Desktop.
AngularJS Directive:Autofocus 基於是否為 Mobile Browser
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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