Creating a 'tab-away' attribute Directive with AngularJS

为君一笑 提交于 2020-01-06 03:14:11

问题


I'm asking this question off the back of:

Dynamically adding an attribute Directive to a transclude Directive in AngularJS

where it was pointed out that the way I was attempting to do something was likely the wrong way to do it. Given that I'm newish to AngularJS, I probably am.

This is what I'm looking to achieve, and how I'm going about it.

If anyone can suggest a more appropriate way - using AngularJS - I'd appreciate it.

The Initial Control/Directive

I'm creating a dropdown panel control using a transcluded directive. It has a button. When you press the button, a div will become visible. The div will contain the transcluded content. I'm fine with all of this.

Tabbing Away

I needed to add functionality so that if you tab away from the control, it closes.

First of all, I attach a 'keypress' event to the document body. This is attached when the dropdown is displayed, and removed when the dropdown is hidden. It must be added/removed at this point to avoid conflict with other instances of the directive (see Handling Click-Aways for two or more of the same directive, which discusses click away, but the scope issues also apply for keypress events).

I then check whether the control has lost focus. To do this, I check whether the directive itself, along with any of it's children has focus following a key press which is tab. The blur logic is as follows:

$scope.directiveHasLostFocus = function () {
  var dropdownWrapper = angular.element("#" + $scope.directiveId + " .dropdown-panel-wrapper");
  if (!dropdownWrapper.is(":focus") && dropdownWrapper.find(":focus").length === 0) {
    return true;
  } else {
    return false;
  }
}

This all works fine.

Refactoring

All the code for this directive is in one directive. It's growing...

I had the thought that I could extract the tab-away functionality into it's own directive.

To do that, I needed to dynamically add/remove the new tab-away directive when the dropdown panel is displayed/hidden (so the events are added/removed appropriately). And that's what led me to:

Dynamically adding an attribute Directive to a transclude Directive in AngularJS

... where I was told I am probably doing it wrong.

Can anyone suggest a better way of going about this using AngularJS? I could not extract it into it's own directive, and it would work fine. But I'm keen to extract it if I can.

Sorry it's such a vague question. I prefer to ask more focused questions, but on this occasion it has to be somewhat high level.

Many thanks.

来源:https://stackoverflow.com/questions/30024053/creating-a-tab-away-attribute-directive-with-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!