February 21, 2014 - No Comments!

Programmatically Setting Focus The AngularJS Way

All standard DOM events, such as focus, blur, click, and others, are represented by their Angular equivalent: ng-focus, ng-blur, ng-click, and the like.

It's cool to see how these directives are implemented. The source code shows us they're all made quite elegantly. Unfortunately, this presents some limitations on what ng-focus can do. You simply supply an expression and Angular will execute it when the DOM event fires.

Example: http://plnkr.co/edit/2fq7LB6CdBdvw7aTois9?p=preview

In this example, I'm attempting to use ng-focus as both an expression that is executed when the field is focused and a way to make an input focused when a boolean is true.

The code is expecting that when isFocused is set to true, the input will gain focus.

As you can see in the example nothing happens when the button is pressed, because executing a boolean as an expression does nothing. 😉

AngularJS doesn't have a different directive to support setting focus so I've written one I'd like to share with everyone.

app.directive('syncFocusWith', function($timeout, $rootScope) {
  return {
    restrict: 'A',
    scope: {
      focusValue: "=syncFocusWith"
    },
    link: function($scope, $element, attrs) {
      $scope.$watch("focusValue", function(currentValue, previousValue) {
        if (currentValue === true && !previousValue) {
          $element[0].focus();
        } else if (currentValue === false && previousValue) {
          $element[0].blur();
        }
      })
    }
  }

That's it! A great use case of using a custom directive.

Here's the above example working as intended using this directive: http://plnkr.co/edit/tHguvMVu418P3mJXOp40

 

Leave a Reply