Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 215
Yasser Shaikh Avatar asked Aug 11 '14 10:08

Yasser Shaikh


Video Answer


2 Answers

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));
      })
    }
  };
});
like image 152
Sudarshan Kalebere Avatar answered Sep 25 '22 13:09

Sudarshan Kalebere


How about:

<input ng-init="$element.focus()">

That worked for me.

like image 31
Ross Rogers Avatar answered Sep 26 '22 13:09

Ross Rogers