Focus on input field in AngularJS (Mini-Challenge 8)

Mini-Challenge 8

ng-challengeAngularJs Mini-Challenges is a growing collection of “Challenges” about the most quirky parts of the AngularJs framework. It encourage you to find and fix common mistakes and subtle bugs, as well as performance issues and bad practices, that non-expert AngularJs programmers may encounter on their endeavours into the depths of the framework.

AngularJs Mini-Challenges does not aim to teach you AngularJs. Former knowledge of the Framework is strongly recommended in order to understand the topics covered in this Challenges. In order to learn the basics of the Framework, please head over to this excellent book:

 

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

 

The Challenge:

What is the ‘Angular way’ to set focus on input field in AngularJS?

More specific requirements:

  1. When a Modal pop-up is opened, set focus on a predefined <input> inside this Modal.

I tried to achieve the first requirement with autofocus, but this works only when the Modal is opened for the first time, and only in certain browsers (e.g. in Firefox it doesn’t work). What would be and elegant way to solve this problem?

 

HTM Code:

<div ng-controller="ModalController">
    <button class="btn" ng-click="open()">Click to Open Modal </button>
<div modal="isOpen" close="close()">
<div class="modal-header">
<h4>Modal</h4>
        </div>
<div class="modal-body">
            Name: <input type="text" autofocus>
        </div>
<div class="modal-footer">
 <button class="btn btn-warning cancel" ng-click="close()">Cancel</button>
        </div>
    </div>
</div>

 

Here you can find a working example:

Here you can find a possible solution

If you feel that the solution is poor or incomplete or there is room for improvement, please share with every one, you can leave a comment.