Skip to content

Instantly share code, notes, and snippets.

@dually8
Created August 6, 2015 20:50
Show Gist options
  • Save dually8/a30e2bd7c36516a24738 to your computer and use it in GitHub Desktop.
Save dually8/a30e2bd7c36516a24738 to your computer and use it in GitHub Desktop.
Angular Get Focus On Show
<div class="box" ng-app="myApp">
<div ng-controller="MyCtrl">
<h1>get focus demo</h1>
<button class="btn btn-default" ng-click="changeFocus()">focus</button>
<div>
<input type="text" ng-show="isFocused" show-focus="isFocused">
</div>
</div>
</div>
var myApp = angular.module('myApp', []);
myApp.directive('showFocus', function($timeout) {
return function(scope, element, attrs) {
scope.$watch(attrs.showFocus,
function (newValue) {
$timeout(function() {
newValue && element[0].focus();
});
},true);
};
});
myApp.controller('MyCtrl', function($scope) {
$scope.isFocused = false;
$scope.changeFocus = function() {
$scope.isFocused = !$scope.isFocused;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.3/angular.js"></script>
.box {
margin-top: 10px;
margin-left: 10px;
}
.demobox {
width: 400px;
min-height: 40px;
padding: 10px;
border: 2px solid #ccc;
margin-bottom: 5px;
}
.icon-refresh {
opacity: 0.65;
}
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment