Angular JS - Focus on form fields

For an Angular JS app I wanted to focus on form fields with a shortcut1. As the framework does not provide a way to focus on any DOM elements, we have to write our own.

We need two parts for this. One directive to hook our functionality:

app.directive('focusOn', function() {  
    return function(scope, elem, attr) {
        scope.$on('focusOn', function(e, name) {
            if(name === attr.focusOn) {

And the function which actually puts the focus on the element:

app.factory('focus', function ($rootScope, $timeout) {  
    return function(name) {
        $timeout(function (){
            $rootScope.$broadcast('focusOn', name);

With the following html:

<input type="text" focusOn="focusIdentifier" />  

You can put focus on the element with the following line:

comments powered by Disqus