0

I have three lines of similar code in multiple directive, which is actually doing some bind an event handler to the "focus".

var ele = $(event.target);
$($(event.target)).attr('tabindex', -1);
$(ele).trigger('focus');

this is creating code duplication issue, creating a service or factory method is not right way, as because i am dealing with DOM manipulation.

is there any way where i can make common method and pass my target and run above code to avoid code duplication.

5
  • are you looking for require option in DDO? Commented Oct 27, 2015 at 13:00
  • 1
    You could create a new directive just for the focus binding Commented Oct 27, 2015 at 13:00
  • @Jai, yes something like that. Commented Oct 27, 2015 at 13:03
  • 1
    FYI, your 3 lines of "code" could be minimized to just one: $(event.target).attr('tabindex', -1);. Commented Oct 27, 2015 at 13:03
  • @Michael: Creating directive and Injecting it on all directive ? Commented Oct 27, 2015 at 13:04

1 Answer 1

1

Normally having code-repetition in some components, like Controllers/Linking functions, isn't a bad Idea because this helps you to make every component indipendent... This is necessary when you work with DOM parts, otherwise you'll get untestable code!

If you need to share Behaviour... Angular has a Directive Concept, so, you can do what you need as angular suggests:

angular
  .module('test', [])
  .directive('scaleTabindex', function() {
    
    return function ScaleTabindexPostLink(iScope, iElement, iAttributes) {
    
      function scaleTabindex(event) {
        var index = Number(iElement.attr('tabindex'));
        
        return iElement.attr('tabindex', index - 1);
      }
      
      iElement.bind('focus', scaleTabindex);
    };
  })
;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<article ng-app="test">
  <button tabindex="100" scale-tabindex>Button 1</button>
  <button tabindex="100" scale-tabindex>Button 2</button>
  <button tabindex="100" scale-tabindex>Button 3</button>
</article>

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you I agree with your point making it component indipendent, but it is repeated many times, need to make one time.
this isn't a repetition, you need to apply the directive where you need to scale the tabindex but the BusinessLogic code is written only once... Directives are multi-instance components!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.