unpollo
unpollo

Reputation: 804

AngularJS architecture: shared utilities across directives

What is the best practice for sharing functionality across multiple directives? Simple use case:

directive('colorInput', function() { // user inputs a hex value })
directive('stringInput', function() { // user inputs a string })

And lets say there's an HTML user assistance bubble that appears when the user focuses into an input. We might then have a function that positions the bubble relative to the input like so:

function setBubble(input, bubble) { // position the bubble }

Is there a way to maintain modularity and encapsulation? Or would this have to go into an angular service or the like? Thanks!

Upvotes: 0

Views: 103

Answers (1)

ssnau
ssnau

Reputation: 367

You should use controller instead. Checkout the section Creating Directives that Communicate in Angular Directive Guide. create a controller named inputGroupController that both your directives require it. Whenever user focus on an input, call baseInputController.setBubble(input, bubble). Take this Plunker: http://plnkr.co/edit/cUhxYmf9b3S1dsRjQXaG?p=preview

Upvotes: 1

Related Questions