2016-06-30 69 views
0

我在Angularjs中並沒有太多的東西,並使用將焦點放在特定元素上的指令。它看起來如下:如何將指令自動對焦調整爲自動對焦=「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」或自動對焦= 「假」。

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,並通過attrs.autoFocus訪問指令的link函數中值

編輯:

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請參閱已編輯的答案.. hasFocus是字符串不是布爾值..如果您認爲值可以稍後更改,則應該使用手錶或觀察者 – Anirudha