Setting Focus on input field with AngularJS

Posted By : Arun Kumar | 31-Dec-2014

Focussing element with javascript can be done by just one line.

document.getElementById("myAnchor").focus();

But we are not supposed to write DOM manipulations code inside controllers of the respective page, Because controllers are meant to act as middle man between modal and view and thats it.

So,rather writing DOM manipulations inside controllers we can make a directive for that and use that directive on the element we are targetting.

Here's the code to do it.

Directive :

angular.module('application').directive('focus', function($timeout, $parse) {
      return {
        link: function(scope, element, attrs) {
          var model = $parse(attrs.focus);
          scope.$watch(model, function(value) {
            if(value === true) { 
              $timeout(function() {
                element[0].focus(); 
              });
            }
          });
        }
      };
    });

   and the html 

<input class="form-control" focus="true" type="text" placeholder="Placeholder"/>

Notice that focus directive we are using here and assigning "true" value to it.

About Author

Author Image
Arun Kumar

Arun is a creative UI Developer

Request for Proposal

Name is required

Comment is required

Sending message..