panagulis72
panagulis72

Reputation: 2169

Autofocus textarea in Angular Material Dialog doesn't work

In a web application I use the Dialog of Angular Material. It contains just a textarea, initially empty. I want to auto-focus on textarea when the user open the modal dialog. How can I do? This is my code but it doesn't work. I've also made a directive, but it doesn't work yet.

Html of modal dialog:

<md-dialog-content>
    <div class="md-dialog-content">
       <md-input-container>
          <label>My textarea</label>            
            <textarea ng-model="myText" md-maxlength="5000" auto-focus></textarea>
       </md-input-container>
    </div>
</md-dialog-content>

Autofocus directive:

angular.module('app').directive("autoFocus", function($timeout) {
  return {
    restrict: 'AC',
    link: function(_scope, _element) {
        $timeout(function(){
            _element[0].focus();
        }, 0);
    }
  };
})

This is the config of the dialog in the controller:

 $mdDialog.show({
                    controller:texateaController,
                    templateUrl: 'texatea.html',
                    parent: angular.element(document.body),
                    targetEvent: event,
                    clickOutsideToClose: false
                    }
                })

Upvotes: 0

Views: 1985

Answers (1)

camden_kid
camden_kid

Reputation: 12813

Here's one way of doing it - CodePen

Markup

<div ng-controller="MyController as vm" class="md-padding" ng-cloak="" ng-app="app">
   <md-button class="md-primary md-raised" ng-click="vm.show($event)">Open</md-button>
</div>

JS

angular.module('app',['ngMaterial'])

  // Inspired by Mark Rajcok'a answer - http://stackoverflow.com/a/14837021/782358
  .directive('autoFocus', function($timeout) {
    return {
      scope: { trigger: '@autoFocus' },
      link: function(scope, element) {
        scope.$watch('trigger', function(value) {
          if (value.toString() === "true") {
            $timeout(function() {
              element[0].focus();
            });
          }
        });
      }
    };
  })

.controller('MyController', function($scope, $mdDialog) {
  this.show = function(ev) {
    $mdDialog.show({
      restrict: 'E',
      template:"<div><md-input-container><textarea auto-focus='true'></textarea></md-input-container></div>" ,
      parent: angular.element(document.body),
      clickOutsideToClose:true,
      targetEvent: ev
    });
  };
});

Upvotes: 2

Related Questions