Skip to content

Instantly share code, notes, and snippets.

@jenslohmann
Last active August 29, 2015 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jenslohmann/4b852942f02c5b8d9ea4 to your computer and use it in GitHub Desktop.
Save jenslohmann/4b852942f02c5b8d9ea4 to your computer and use it in GitHub Desktop.
How to move focus to a field the angular way
...
<textarea focus-on="IWantFocusWhenButtonClicked"></textarea>
<button ng-click="doFocus()">Focus</button>
...
...
$scope.doFocus = function() {
$scope.$broadcast("focus:IWantFocusWhenButtonClicked");
}
angular.directive('focusOn', ['$timeout', ($timeout) => {
return {
restrict: 'A',
link: (scope, element, attr) => {
scope.$on("focus:" + attr.focusOn, () => {
$timeout(element[0].focus());
});
}
};
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment