Yasser Yasser - 4 months ago 95
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

autofocus
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>
<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>
<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>
</div>


How do I get this to work ?

Answer

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) {
        console.log('value=',value);
        if(value === true) { 
          $timeout(function() {
            element[0].focus(); 
          });
        }
      });
      element.bind('blur', function() {
        console.log('blur')
        scope.$apply(model.assign(scope, false));
      })
    }
  };
});