angular set focus on input field (Mini-Challenge 8) Answer

Check out Mini-challenge 8 Instructions (angular set focus)

Answer:

The Angular way to set the focus to an element inside a modal, is with a directive (since this is related to the DOM and Events).

When a Modal is opened, set focus on a predefined <input> inside this Modal.angular set focus
Define a directive and have it $watch a property/trigger so it knows when to focus the element:

Name: <input type="text" focus-me="isOpen">

 

app.directive('focusMe', function($timeout, $parse) {
  return {
    //scope: true,   // optionally create a child scope
    link: function(scope, element, attrs) {
      var model = $parse(attrs.focusMe);
      scope.$watch(model, function(value) {
        if(value === true) { 
          $timeout(function() {
            element[0].focus(); 
          });
        }
      });
      // on blur event:
      element.bind('blur', function() {
         scope.$apply(model.assign(scope, false));
      });
    }
  };
});

Notice that we also added a code for when the element loose the focus (blur) it sets the isOpen property back to false.

Here is a working example:
http://jsfiddle.net/7L8vqf8u/3/

Recommendations:

It is highly recommended try to avoid as much as possible the use of the $watch service. This is another possible solution using angular events:

app.directive('focusOn', function($timeout) {
   return function(scope, element, attrs) {
      scope.$on(attr.focusOn, function(e) {
          $timeout(function() {
            element[0].focus(); 
          });
      });
   };
});

 

Now you can put your directive in the view:

<input type="text" focus-on="isOpen" />

 

and then, in your controller:

$scope.open = function () {
    $scope.$broadcast('isOpen');
};

 

book

Book Tip

ng-book – The Complete Book on AngularJS
Ready to master AngularJS? What if you could master the entire framework – with solid foundations – in less time without beating your head against a wall?


Amazon

 

If you have a better solution on how angular set focus, for this challenge, different from the proposed solution on this post, don’t be shy and share it with us 🙂 you can leave a message on this blog or you can twit me @JoMendezdev.