Angular Material Dialog中的自动对焦textarea不起作用

时间:2016-09-09 13:22:01

标签: javascript angularjs angular-material mddialog

在Web应用程序中,我使用Angular Material的对话框。它只包含一个textarea,最初是空的。我想在用户打开模态对话框时自动对焦textarea。我能怎么做?这是我的代码,但它不起作用。我也做了一个指令,但它还没有用。

模态对话框的HTML:

<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>

自动对焦指令:

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

这是控制器中对话框的配置:

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

1 个答案:

答案 0 :(得分:2)

这是一种做法 - CodePen

标记

<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
    });
  };
});