2016-06-30 8 views
0

私はAngularjsであまりよくありませんし、特定の要素に焦点を当てるディレクティブを使用します。これは、次のようになります。ディレクティブオートフォーカスをauto-focus = "true"/"false"に適合させる方法は?

appModule.directive('autoFocus', function ($timeout) { 
    return { 
     restrict: 'AC', 
     link: function (scope, element, attrs) { 
      $timeout(function() { 
       element[0].focus(); 
      }, 0); 
     } 
    }; 
}); 

使用量は、次のようになります。

<button auto-focus class="uui-button lime-green btn" ng-click="copyToClipboard()"> 
    Copy 
</button> 

私は書く能力を持っている上記のディレクティブを再配置したい:オートフォーカス=「true」またはオートフォーカスを= "false"。

UPDATE:

以下に示すように、私は、コードを更新したが、それはそれが焦点では動作しませんが、常にあるにかかわらず、私は「=オートフォーカス=「true」またはオートフォーカスを書きます偽 "です。

appModule.directive('autoFocus', function ($timeout) { 
    return { 
     restrict: 'AC', 
     link: function (scope, element, attrs) { 
      var hasFocus = attrs.autoFocus; 
      if (hasFocus) { 
       $timeout(function() { 
        element[0].focus(); 
       }, 0); 
      } 
     } 
    }; 
}); 

答えて

1

あなたはtrueまたはfalseにプロパティを設定し、ディレクティブのlink関数内でattrs.autoFocus経由

編集値にアクセスすることができます

appModule.directive('autoFocus', function ($timeout) { 
    return { 
     restrict: 'AC', 
     link: function (scope, element, attrs) { 
      var hasFocus = attrs.autoFocus; 
      if (hasFocus ==="true") { 
       $timeout(function() { 
        element[0].focus(); 
       }, 0); 
      } 
     } 
    }; 
}); 
+0

あなたは、上記のアップデートをご覧くださいでした。 – tesicg

+0

@tesicg編集したansを見てください。hasFocusは文字列ではありません。また、値が後で変更できると思う場合は、時計またはオブザーバーを使用する必要があります – Anirudha

関連する問題