Yasser Yasser - 1 year ago 346
AngularJS Question

Angular Bootstrap Modal popup autofocus not working

I have implemented a bootstrap modal using angular bootstrap which works fine.

Here is a plunker link for the code I have used.

In my modal I have only one input field (textbox) which needs to be filled by the user and a save and cancel button. I want that when the modal is shown the textbox should have the focus.

I tried the

attribute which works otherwise not working in this case.

Pasted below is my html on the modal.

<div class="modal-header panel panel-heading">
<button type="button" class="close" ng-click="ok()">×</button>
<h4 class="modal-title">Add Project</h4>
<div class="modal-body">
<input autofocus="autofocus" type="text" class="form-control" id="ProjectName" placeholder="Enter project name here" data-ng-model="ProjectName" tab-index="1"/>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="ok()" tab-index="2">Create</button>
<button class="btn btn-default" ng-click="cancel()" tab-index="3">Cancel</button>

How do I get this to work ?

Answer Source

Here is a plunker link with the fix: you need to create a directive for it

app.directive('focusMe', function($timeout, $parse) {
  return {
    link: function(scope, element, attrs) {
      var model = $parse(attrs.focusMe);
      scope.$watch(model, function(value) {
        if(value === true) { 
          $timeout(function() {
      element.bind('blur', function() {
        scope.$apply(model.assign(scope, false));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download