2016-09-09 8 views
0

ウェブアプリケーションでは、角度材料のダイアログを使用します。それは最初は空のテキストエリアだけを含んでいます。ユーザーがモーダルダイアログを開いたときに、テキストエリアに自動的にフォーカスしたいと思います。どのようにできるのか?これは私のコードですが、うまくいきません。私も指示を出しましたが、まだ動作しません。角度材料ダイアログのオートフォーカステキストエリアが機能しない

モーダルダイアログの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 
        } 
       }) 

答えて

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 
    }); 
    }; 
}); 
関連する問題