var app = angular.module('plunker', []);
app.directive('autoFocus', function($timeout) {
return {
link: function (scope, element, attrs) {
attrs.$observe("autoFocus", function(newValue){
if (newValue === "true")
$timeout(function(){element.focus()});
});
}
};
});
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>Simple auto-focus directive example</title>
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>document.write('<base href="' + document.location + '" />');</script>
<script data-require="angular.js@1.2.x" src="https://code.angularjs.org/1.2.16/angular.js" data-semver="1.2.16"></script>
<script src="app.js"></script>
</head>
<body>
<button ng-click="isVisible1 = !isVisible1">Toggle input 1</button>
<input ng-show="isVisible1" value="auto-focus off" />
<br>
<button ng-click="isVisible2 = !isVisible2">Toggle input 2</button>
<input ng-show="isVisible2" auto-focus="{{ isVisible2 }}" value="auto-focus on" />
</body>
</html>